Nov 23, 20266 min read

Eventual Consistency in Microservices

What eventual consistency means in a backend split into services, where it shows up (read replicas, events, caches), the user-facing bugs it causes, and the patterns that keep it manageable: read-your-writes, idempotent consumers, versioned updates and the outbox.

Illustration for Eventual Consistency in Microservices

Eventual consistency is what you get as soon as one piece of data lives in two places and the second copy is updated after the first: a read replica, a search index, a cache, or another service's table filled from events.

It is usually the right trade, since it keeps services independent and writes fast, but it creates a specific set of bugs that users notice, and each has a known fix.

At a glance

SourceTypical lagBug users noticeFix
Read replicasMilliseconds to seconds"I saved it and it is gone"Read your own writes from the primary
Event-driven read modelsSecondsTotals or lists missing the latest itemReturn data from the command, show pending state
CachesUp to the TTLOld prices or settingsInvalidate on write, short TTL for volatile data
Search indexesSeconds to minutesNew item not foundShow it from the primary store until indexed
Cross-service copiesSeconds, longer on failureTwo services disagreeIdempotent, versioned consumers and reconciliation

Where it comes from

Werner Vogels' Eventually Consistent defines it as a guarantee that, without new updates, all accesses eventually return the last written value, with the window of inconsistency depending on replication delay and load. In a typical backend that window appears in a few places:

  • Read replicas. RDS and Cloud SQL replicas apply changes asynchronously, and the RDS read replica documentation notes they can lag behind the primary, which shows up as ReplicaLag.
  • Events. An OrderPlaced event updates customer stats, search and analytics after the order commits, never in the same transaction.
  • Caches. A cached value stays stale until it expires or is invalidated.

Some managed stores now avoid it: Amazon S3 has offered strong read-after-write consistency since 2020, and DynamoDB lets you choose strongly consistent reads per request, as its read consistency docs describe.

The bugs it causes

The classic one is a user editing their profile, being redirected to a page that reads from a replica, and seeing the old name. Others are an order list missing a newly placed order, a stock count that goes negative because two services each saw "1 left", and a dashboard total that does not match the detail rows. None of these are data loss, which is why they tend to get dismissed until a support ticket arrives.

Patterns that keep it manageable

  • Read your own writes. Return the new state from the write endpoint, and route a user's reads to the primary for a short time after they write.
  • Keep invariants in one place. Rules like "never oversell" must be checked where the data is owned, with a transaction or a conditional update, not in a service reading a copy.
  • Idempotent consumers. At-least-once delivery means duplicates, so record processed event IDs or write with upserts.
  • Versioned updates. Carry a version or timestamp in each event and ignore anything older than what is stored, so a late message cannot overwrite newer data.
  • Publish reliably. Writing to the database and publishing an event are two operations, so use a transactional outbox when a lost event is unacceptable.
  • Reconcile. A periodic job that compares copies and repairs drift catches whatever the other patterns miss.

Best fit: eventual consistency for derived views and cross-service copies, strong consistency for the invariants a single service owns.

Event-driven read models in Encore

Encore

Encore is a backend framework with built-in infrastructure, so the topic between two services is declared in code next to the publisher, and the subscriber lives in the service that owns the copy. In this TypeScript example the orders service publishes OrderPlaced, and a customer stats service keeps a read model that is idempotent and ignores stale events (each folder has an encore.service.ts declaring the service):

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

// orders/events.ts import { Topic } from "encore.dev/pubsub"; export interface OrderPlaced { orderId: string; customerId: string; totalCents: number; placedAt: string; // ISO timestamp, used to ignore out-of-order events } export const orderPlaced = new Topic<OrderPlaced>("order-placed", { deliveryGuarantee: "at-least-once", });
// stats/stats.ts import { api } from "encore.dev/api"; import { Subscription } from "encore.dev/pubsub"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { orderPlaced } from "../orders/events"; // migrations/1_create_stats.up.sql: // CREATE TABLE processed_events (order_id text PRIMARY KEY); // CREATE TABLE customer_stats (customer_id text PRIMARY KEY, // order_count int NOT NULL, total_cents bigint NOT NULL, // last_order_at timestamptz NOT NULL); const db = new SQLDatabase("stats", { migrations: "./migrations" }); new Subscription(orderPlaced, "update-customer-stats", { handler: async (e) => { await using tx = await db.begin(); // Duplicate delivery: the insert does nothing and we stop here. const fresh = await tx.queryRow` INSERT INTO processed_events (order_id) VALUES (${e.orderId}) ON CONFLICT DO NOTHING RETURNING order_id `; if (!fresh) { return; } await tx.exec` INSERT INTO customer_stats (customer_id, order_count, total_cents, last_order_at) VALUES (${e.customerId}, 1, ${e.totalCents}, ${e.placedAt}::timestamptz) ON CONFLICT (customer_id) DO UPDATE SET order_count = customer_stats.order_count + 1, total_cents = customer_stats.total_cents + EXCLUDED.total_cents, last_order_at = GREATEST(customer_stats.last_order_at, EXCLUDED.last_order_at) `; await tx.commit(); }, }); interface Stats { orderCount: number; totalCents: number; } export const get = api( { expose: true, method: "GET", path: "/stats/:customerId" }, async ({ customerId }: { customerId: string }): Promise<Stats> => { const row = await db.queryRow<{ order_count: number; total_cents: number }>` SELECT order_count, total_cents FROM customer_stats WHERE customer_id = ${customerId} `; return { orderCount: row?.order_count ?? 0, totalCents: Number(row?.total_cents ?? 0) }; }, );

Recording the event ID and updating the stats in one transaction makes the handler safe to run twice, and GREATEST keeps last_order_at correct when events arrive out of order. The Pub/Sub docs describe the at-least-once delivery the handler is written for, and on AWS the topic becomes SNS with SQS subscriptions, on GCP a Pub/Sub topic, both with dead-letter handling as the AWS infrastructure docs explain. The databases docs cover transactions.

encore run starts the topic, both services and their databases locally, and the local development dashboard traces the publish and the subscriber run, so you can see how long the copy takes to catch up. An AI coding agent adding a second read model, say for search, can copy the subscriber and test duplicate delivery against local infrastructure in the same change, and a test can publish the same event twice and assert the count only moved once.

Best fit: services that share data through events and want duplicate and out-of-order delivery handled where the copy is written.

Frequently asked questions

What is eventual consistency in microservices?

Eventual consistency means that after a write, other services or replicas may return the old value for a while, but they converge on the new value if no further writes happen. It appears whenever data is copied asynchronously, through read replicas, events or caches.

How do you handle eventual consistency in a user interface?

Return the written data from the command that changed it so the client can show it immediately, read from the primary for the user's own recent writes, and label derived views such as totals or search results as updating when they lag.

How do I keep event consumers consistent when messages arrive twice or out of order?

Make each consumer idempotent by recording processed event IDs or using upserts, and ignore stale updates by comparing a version or timestamp carried in the event against the one already stored.

How does Encore handle events between services?

Services publish to a Pub/Sub topic declared in code and other services subscribe with a handler. Encore runs the topics locally with encore run and provisions SNS and SQS on AWS or Pub/Sub on GCP, with at-least-once delivery, so handlers should be idempotent.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders