▚ The Software Engineer's Field Manual
Chapter E7 · Primer + senior drill

Microservices — Primer + 150-Question Drill

"Splitting a system into services does not remove any of its problems. It moves every one of them onto the network, where they are harder to see and impossible to roll back with one commit."

150 questions · answers collapsed For: ~9-year engineers prepping the senior round Heavy on: sagas · outbox · retries and idempotency · cascading failure · tracing

01 · Why this primer existsYou Work in a Service Architecture Every Day — Nobody Explained the Bill

Splitting a system into services buys you independent deployment and costs you a network between every two objects. This chapter is about knowing which trade you are making before you make it.

After nine years you have almost certainly shipped code into a system made of many services.

You have written a REST client with a timeout, added @Retryable or a Resilience4j annotation because someone said to, published an event to Kafka, and then spent an afternoon in a tracing tool wondering why one checkout touched forty different processes.

What the senior interview asks is the layer underneath those habits: why does a retry without an idempotency key create duplicate orders? What exactly does a circuit breaker measure before it opens?

When an order spans four services and the third one fails, who undoes the first two, and what does the customer see in the meantime? These are not trick questions.

They are the questions that separate a person who has used microservices from a person who could be trusted to design one, and every one of them is answerable from a small set of ideas this primer teaches in plain words.

Those ideas are four, and a senior candidate is expected to hold all of them in their head at once:

  1. The boundary: where you cut, and why the cut follows the business, not the code.
  2. The network call: what can go wrong on it, and the four tools that make it survivable — timeouts, retries, idempotency, breakers.
  3. The split database: why each service owns its data, and how work that spans services is made reliable with sagas and the outbox pattern.
  4. The operating discipline: traces, error budgets, canaries and contract tests, which let a hundred people change a hundred services without breaking each other.

The senior skill is to say, without hesitation, which one of the four a given incident belongs to.

The page has two halves.

The primer (sections 02–06) walks the five topics in order: why and when to split at all; communication and resilience between services; data ownership, sagas, and the outbox; operability and delivery; and finally how service systems scale and how they fail as a whole.

Each chapter has at least one diagram, one complete piece of code or configuration you can actually run, and a Brain Power question to answer before you read on.

The drill (sections 07–10) is 150 interview questions — knowledge questions about mechanisms, production scenarios you must diagnose in order, and design exercises with trade-offs — every answer collapsed behind a Reveal answer control.

The method that works is the one from Chapter E3: read the question, say your whole answer aloud as if the interviewer were in the room, and only then reveal. If you skip the saying-aloud step, you are reading, not drilling.

Three neighbours matter. the Distributed Systems primer holds the theory this page leans on — consensus, the CAP trade-off, clocks and ordering — and this page refers there rather than repeating it. Chapter E4 covers the Spring Boot machinery every Java code sample here assumes. Chapter E10 covers where the services actually run. Read this page after E4 and before E6 (API design), because the shape of an API is much easier to judge once you understand what happens to it on the network.

How every pattern in this chapter is laid out

Each design pattern gets its own heading, Pattern: Name, so you can find it again. Under that heading the steps always come in the same order:

  1. The problem: what goes wrong without it, shown on the order / payment / inventory example.
  2. How it works: numbered steps and a picture of the pattern working.
  3. The setup: the smallest code or configuration.
  4. What you see: evidence with and without the pattern, in the same layout.
  5. The trap: the classic way the pattern itself fails or is misapplied.
  6. When to use it / when not: a short Works / Fails list.
  7. Interview takeaway: the sentence to say aloud.

Pattern map: every pattern in this chapter

Use this table as the index: pick the problem you are looking at, follow the link to the pattern.

Pattern map — the problem each pattern solves and where to read about it
PatternProblem it solvesSection
Modular MonolithYou want team boundaries without paying for a network between every module.02 Why and when to split
Bounded ContextOne shared model of “customer” tangles every team's changes together.02 Why and when to split
Strangler FigA big-bang rewrite cannot ship until it is finished and cannot be rolled back.02 Why and when to split
Anti-Corruption LayerA legacy or foreign model leaks its names and rules into your clean new model.02 Why and when to split
TimeoutA call with no deadline holds a thread for as long as the callee stalls.03 Communication
Retry with Backoff and JitterTransient failures deserve a second try, but synchronised retries knock a recovering service over again.03 Communication
Circuit BreakerCallers keep hammering a failing dependency and use up their own threads waiting.03 Communication
BulkheadOne slow dependency consumes every thread and starves unrelated work.03 Communication
Service DiscoveryInstances come and go, so callers cannot hard-code addresses.03 Communication
API GatewayEvery client would have to know, authenticate against and rate-limit every internal service.03 Communication
Backend for Frontend (BFF)One general API over-fetches for mobile and under-fetches for web.03 Communication
Sidecar and Service MeshEvery service re-implements mutual TLS, retries and telemetry in its own language.03 Communication
Database per ServiceShared tables couple services, so nobody can change a schema or deploy alone.04 Data, sagas, outbox
Saga (Orchestration)A business transaction spans services with no shared ACID transaction, and a middle step fails.04 Data, sagas, outbox
Saga (Choreography)The same cross-service transaction, but with no central coordinator to own the flow.04 Data, sagas, outbox
Transactional OutboxSaving to the database and publishing to the broker can succeed or fail separately.04 Data, sagas, outbox
Idempotent ConsumerAt-least-once delivery means the same message arrives twice and its effect is applied twice.04 Data, sagas, outbox
Dead-Letter QueueOne poison message blocks or loops a consumer forever.04 Data, sagas, outbox
CQRSOne model cannot serve transactional writes and cross-service read queries equally well.04 Data, sagas, outbox
Event SourcingCurrent-state tables lose the history of how the state came to be.04 Data, sagas, outbox
Distributed TracingOne request crosses many processes and no single log shows the whole story.05 Operability and delivery
Consumer-Driven ContractsA provider change breaks a consumer nobody told, and end-to-end tests are too slow to catch it.05 Operability and delivery
Blue-Green DeploymentDeploying and releasing are one risky step with a slow rollback.05 Operability and delivery
Canary ReleaseA bad version reaches every user before anyone sees the error rate.05 Operability and delivery
Externalized ConfigurationConfig baked into the image forces a rebuild per environment and leaks secrets.05 Operability and delivery
Rate LimitingOne noisy client consumes capacity meant for everyone.06 Scaling and failure
Load SheddingUnder overload every request gets slow instead of a few failing fast.06 Scaling and failure
Cache-AsideEvery read hits the slow shared database, and a naive cache drifts away from it.06 Scaling and failure
Health ChecksThe platform keeps sending traffic to, or keeps alive, an instance that cannot serve.06 Scaling and failure

02 · The primerWhy and When to Split — Monolith, Modular Monolith, Microservices

The only real reason to split is independent deployability. Everything else on the list — scaling, team autonomy, technology choice — a modular monolith gives you more cheaply.

Start with a number. A well-run monolith at a mid-sized company deploys perhaps twice a week, because every deploy carries every team's changes and every team has to be ready.

The same company after a careful split into twelve services deploys around forty times a day, because each team ships its own service when it is ready.

That is the whole reason microservices exist: independent deployability — the ability of one team to change and release its piece without coordinating with the others.

Everything else people list as a benefit (scaling one hot part, using a different language, isolating a crash) is real but secondary. If you do not need teams to move independently, you do not need microservices, and you should say so in the interview.

Now the bill. That same split turned roughly two hundred in-process method calls into two hundred network calls. A method call takes about 50 nanoseconds and cannot fail on its own.

A call across a data centre takes about 500 microseconds to a few milliseconds — ten thousand times slower — and can time out, return a partial answer, or succeed while the reply is lost.

The single database with foreign keys and one transaction became twelve databases with no transaction across them. The stack trace became a distributed trace. The single deploy became forty, each of which may break a consumer that was written against last week's version.

A microservice architecture is a decision to accept every one of those costs in exchange for team independence, and a senior engineer is the person in the room who can price that trade honestly.

The setup: one checkout in the running order platform, before and after the split. The same three steps, but the cost moves.

Make the invisible visible: the same three steps as in-process calls and as network calls, with the cost of each.

what a split changesruns offline
# illustrative numbers
BEFORE (one process)                          AFTER (three services)
checkout()                                    checkout()
  orders.save()         ~0.05 ms  ✓             orders-db INSERT         ~2 ms
  payments.charge()     ~0.05 ms  ✓             HTTP POST /payments      ~3 ms   ✗ can time out
  inventory.reserve()   ~0.05 ms  ✓             HTTP POST /reservations  ~3 ms   ✗ can time out
  commit (one tx)       all or nothing ✓        3 commits, 3 databases   ✗ no all-or-nothing

The trace: payment succeeds, then the inventory call times out.

what is committed whereruns offline
step                       orders-db     payments-db      inventory-db
1 save order               o-1 NEW  ✓    -                -
2 charge card              o-1 NEW       p-1 CHARGED  ✓   -
3 reserve stock (timeout)  o-1 NEW       p-1 CHARGED      (no row)  ✗
Result: the customer is charged for an order with no reservation, and no rollback spans the three databases.

What you see: a half-finished checkout that the old single transaction would have made impossible.

consoleruns offline
# illustrative output
POST /orders  ->  500 Internal Server Error  (inventory-service: Read timed out after 800 ms)
payments-db:  SELECT status FROM payments WHERE order_id='o-1'  ->  CHARGED
inventory-db: SELECT * FROM reservations WHERE order_id='o-1'    ->  0 rows

Why: every arrow that used to be a method call is now a message over a network that can lose, delay or duplicate it, and every database commits on its own. Sections 03 and 04 are the tools for exactly this picture.

Bridge: you already know the shape from good code

You have spent years keeping packages loosely coupled and highly cohesive. A service boundary is the same idea with a harder wall.

Inside a monolith, a "boundary" is a package whose internals you are asked not to touch; any developer can ignore the request with one import.

A service boundary makes the request physical: the only way in is the published API, and the only shared thing is the contract.

The principle is identical — hide what changes together, expose only what others need — but the cost of getting it wrong goes from "a messy import" to "two teams who cannot ship without a meeting".

Pattern: Modular Monolith

A modular monolith is one deployable program whose code is divided into modules with enforced boundaries — each module has a public interface, its own tables (often its own database schema), and a build rule (Spring Modulith, or ArchUnit tests) that fails the build if module A reaches into module B's internals.

The problem: in a plain monolith a package boundary is a request, and one import ignores it. Months later nobody can change a table without reading every package.

what goes wrongruns offline
# illustrative output
payments/RefundService.java   import shop.orders.internal.OrderRow;   ✗ compiles, nobody notices
Change OrderRow.status from String to an enum:
  -> orders, payments, shipping fail to compile; 3 teams blocked on one pull request

How it works:

  1. One module per business area: orders, payments, inventory, each a top-level package.
  2. Public API only: the module's base package holds the types others may use; sub-packages such as orders.internal are private.
  3. Own tables: each module owns its tables or schema, and other modules ask through the public interface instead of joining.
  4. Build verifies it: a test fails if one module reaches into another's internals.
  5. Events between modules: modules publish events instead of calling each other directly where they can.
module layoutruns offline
shop/
  orders/            <- public: OrderService, OrderPlaced (event)
    internal/        <- private: OrderRow, OrderRepository
  payments/          <- public: PaymentService
    internal/
  inventory/         <- public: InventoryService
    internal/
payments -> orders.OrderService      ✓ public type
payments -> orders.internal.OrderRow ✗ build fails

You keep one deploy, one database transaction, one stack trace, and you still get the discipline that would let you cut a module out into a service later if a team actually needs to ship independently.

As of Aug 2026 Spring Modulith 2.x, which pairs with Spring Boot 4, verifies these boundaries at test time and can publish events between modules through a persisted event log, which is an in-process version of the outbox pattern you will meet in section 04.

The setup: one test class is the whole enforcement.

ModularityTests.javaruns offline
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;

class ModularityTests {

    @Test
    void verifiesModuleBoundaries() {
        // ✅ FIX: fails the build when a module touches another module's internals
        ApplicationModules.of(ShopApplication.class).verify();
    }
}

What you see: the same illegal import, with and without the test.

consoleruns offline
# illustrative output
without the test:  mvn verify  ->  BUILD SUCCESS   ✗ the import ships
with the test:     mvn verify  ->  ModularityTests.verifiesModuleBoundaries FAILED  ✓ caught
                   (the failure names module 'payments' and the non-exposed type in module 'orders')

The trap: modules that share tables or JPA entities are modules in name only. If payments joins orders' tables directly, cutting it out later means untangling the data, which is the hard part.

what goes wrongruns offline
payments module:  SELECT ... FROM orders.order_row JOIN payments.payment ...   ✗ shared schema
Cut payments into a service  ->  that JOIN becomes a network call per row, and nothing tells you where

When to use it / when not: it is the default shape for a first system and for a team that is not yet blocked by coordination.

Monolith Modular monolith Microservices one process · one deploy orders payments inventory any code calls any code one database · one transaction one process · one deploy orders payments inventory public API only · build enforces one database · schema per module orders payments inventory every call crosses the network can time out · can duplicate · can be lost db db db three deploys · three databases · no shared transaction one deploy · everyone waits for everyone one deploy · boundaries already drawn What changes left to right: the deploy unit, the transaction boundary, and where failures can happen
Fig. E7.1 — The three shapes side by side. The modular monolith already has the boundaries; only the last step puts a network between them, and that step is where every new failure mode enters.

Where to cut: bounded contexts in plain words

Pattern: Bounded Context

A bounded context is a part of the business inside which a word has exactly one meaning. It comes from domain-driven design (DDD), and it is the good answer to "how big should a service be?" (the bad answer is lines of code).

The problem: take the word "customer". To the sales team a customer is a lead with a pipeline stage. To billing it is an account with a payment method and an outstanding balance. To shipping it is a name and an address. Those are three different objects that happen to share a name.

one shared customer tableruns offline
customer   (one table, three teams)
id | pipeline_stage | payment_method | balance | ship_name | ship_address
7  | QUALIFIED      | visa-4242      | 0.00    | A. Rao    | 12 Elm St
Sales adds lead_score         -> billing's report query breaks
Shipping renames ship_address -> sales' export breaks
Every change needs three teams to agree  ✗

Trying to keep one Customer table that serves all three is how monoliths become tangled: every team adds columns, and a change for shipping breaks a report for billing.

How it works:

  1. Find where the words change meaning: listen for the same word used differently by different teams.
  2. Give each context its own model: sales, billing and shipping each get their own "customer".
  3. Translate at the border: when contexts need to talk, they exchange a small agreed message (usually just an id and the facts the other side needs).
  4. Cut the service along the context: services cut along bounded contexts tend to be stable, because the business meaning behind them is stable.
three models, one borderruns offline
Sales context     Lead      { id, stage }
Billing context   Account   { id, paymentMethod, balance }
Shipping context  Recipient { id, name, address }
Border event      OrderPlaced { orderId, customerId, total }   <- carries ids and the facts others need, not the other model

The setup: three small types, one per context, with no shared Customer class.

contexts.javaruns offline
// sales module
record Lead(String id, String stage) {}

// billing module
record Account(String id, String paymentMethod, java.math.BigDecimal balance) {}

// shipping module
record Recipient(String id, String name, String address) {}

// ❌ TRAP: one shared "Customer" class that all three import
// ✅ FIX: each module owns its own model and exchanges only ids through events

What you see: the cost of the same change before and after the cut.

change impactruns offline
# illustrative output
Add Customer.lead_score
  one shared table:   queries to review: billing 4, shipping 3, sales 6   -> 3 teams, 1 meeting
  bounded contexts:   queries to review: sales 6 only                     -> 1 team, 0 meetings

The trap: cutting along nouns or technical layers instead. A "user service" that every other service needs on every request becomes the thing everyone is blocked on (the Brain power question below shows its failure).

blast radiusruns offline
order-service  --sync-->  user-service     user-service has a bad deploy (4 min)
cart-service   --sync-->  user-service     order  ✗   cart ✗   catalog ✗   <- every caller fails
catalog        --sync-->  user-service     cut along a noun, not a business capability

When to use it / when not: use it before you draw any service boundary.

Conway's law: the org chart is the architecture

The second guide is Conway's law: a system's structure ends up mirroring the communication structure of the organisation that built it. If three teams build a compiler, you get a three-pass compiler.

Read forwards it is a warning; read backwards it is a tool, sometimes called the inverse Conway manoeuvre.

If you want a service boundary to hold, put one team on each side of it and give that team full ownership — the code, the database, the on-call pager, the deploy button.

A service owned by nobody, or by three teams at once, decays into a shared library with a network hop.

team to service ownershipruns offline
# illustrative
Team Orders    owns  order-service      + orders-db     + pager + deploy button   ✓ one owner
Team Payments  owns  payment-service    + payments-db   + pager + deploy button   ✓ one owner
inventory-service    owned by Teams A, B and C                                    ✗ decays into a shared library with a network hop

Cutting over safely: the strangler fig and the anti-corruption layer

Once you decide to split, two patterns decide whether the migration is calm or a rewrite that never ships. The strangler fig moves traffic gradually; the anti-corruption layer keeps the old model from leaking into the new service.

Pattern: Strangler Fig

The strangler fig pattern replaces a legacy system piece by piece behind a router, so old and new run side by side until the old one has nothing left to do. It is named after the vine that grows around a tree until the tree is gone.

The problem: a big-bang rewrite of the order monolith takes eighteen months, ships nothing until the end, and cannot be rolled back on cutover night.

big-bang timelineruns offline
month  0          6          12         18
legacy [=== keeps changing ============]  new features land in the old code
rewrite[=== builds a copy of last year ==]  ✗ target moves, no value shipped
cutover night: 100% of traffic switches at once, rollback = restore the old system, if it still matches

How it works:

  1. Put a router in front: a gateway or proxy that today forwards everything to the legacy system.
  2. Pick one slice: for example /api/orders, and build it as a new service.
  3. Route that slice to the new service: often to a small share of traffic first.
  4. Repeat: slice by slice, until the legacy system receives nothing.
  5. Switch the old system off: a real, scheduled step, not an afterthought.
routing over timeruns offline
# illustrative
          /api/orders    /api/invoices   /api/shipping
week  0   legacy 100%    legacy 100%     legacy 100%
week  6   new     10%    legacy 100%     legacy 100%    <- first slice, small share
week  8   new    100%    legacy 100%     legacy 100%
week 20   new    100%    new    100%     new    100%    <- legacy switched off

The setup: a route table at the gateway; the more specific path is listed first so it wins.

gateway-routes.ymlruns offline
# the property prefix differs between Spring Cloud Gateway releases; check yours
spring:
  cloud:
    gateway:
      routes:
        - id: orders-new
          uri: http://order-service:8080
          predicates:
            - Path=/api/orders/**
        - id: legacy-everything-else
          uri: http://legacy-shop:8080
          predicates:
            - Path=/**

What you see: each request lands on exactly one side, and rolling back a slice is one line in the route table.

gateway access logruns offline
# illustrative output
GET /api/orders/42     -> order-service   200   (new)
GET /api/invoices/9    -> legacy-shop     200   (not migrated yet)
rollback of orders:    remove the orders-new route -> traffic returns to legacy-shop in seconds

The trap: two copies of the data. While old and new both write orders, they can disagree, and a strangler that never retires the legacy system gives you two systems to run forever.

what goes wrongruns offline
legacy orders table:   o-9  SHIPPED
order-service db:      o-9  CREATED      ✗ two sources of truth, no owner
Fix: one side owns each slice; the other reads through its API or a one-way copy

When to use it / when not: use it for any migration that must keep running while it changes.

Pattern: Anti-Corruption Layer

An anti-corruption layer (ACL) is a translator at the border of a new service that converts a legacy or third-party model into the new service's own model, so the old names and rules stop at the border.

The problem: the new order service calls the legacy shop and starts using its fields directly. Within a month the legacy status codes are in every class.

legacy model leakingruns offline
legacy reply:   { "cust_stat": "A", "ord_dt": "20260412", "tot": "1999" }   (tot in cents, as text)
new service code that uses it directly:
  if ("A".equals(r.cust_stat))  ...        ✗ what is "A"?
  LocalDate.parse(r.ord_dt, ...)           ✗ date parsing in every class
  new BigDecimal(r.tot)                    ✗ cents treated as euros: silently wrong

How it works:

  1. Define your own model first: the types the new service wants, with clear names.
  2. Write one translator: the only class that knows the legacy shape.
  3. Call the legacy system only through it: the rest of the service sees the new model.
  4. Delete it with the legacy system: the translator disappears when the old system does.

The setup: one translator class at the border.

LegacyOrderTranslator.javaruns offline
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

record LegacyOrder(String cust_stat, String ord_dt, String tot) {}
record Order(boolean customerActive, LocalDate placedOn, BigDecimal total) {}

class LegacyOrderTranslator {
    private static final DateTimeFormatter D = DateTimeFormatter.BASIC_ISO_DATE;   // yyyyMMdd

    Order toOrder(LegacyOrder l) {
        return new Order(
            "A".equals(l.cust_stat()),                       // ✅ FIX: legacy code "A" means active, said once
            LocalDate.parse(l.ord_dt(), D),
            new BigDecimal(l.tot()).movePointLeft(2));       // cents to currency units, said once
    }
}

What you see: the same legacy reply, translated.

consoleruns offline
# illustrative output
in :  { "cust_stat": "A", "ord_dt": "20260412", "tot": "1999" }
out:  Order[customerActive=true, placedOn=2026-04-12, total=19.99]

The trap: letting the translator grow business rules, or copying it into every service. Then it is a shared library every team must change together, which is the coupling you were avoiding.

what goes wrongruns offline
legacy changes tot to euros  ->  one translator to fix  ✓
translator copied into 5 services  ->  5 fixes, 5 deploys, 1 missed  ✗

When to use it / when not: use it wherever your clean model touches a model you do not control.

The running example, as configuration

The rest of this primer uses one small system: an order service that accepts checkouts, a payment service that charges cards, and an inventory service that reserves stock, each with its own PostgreSQL database, talking through Kafka. Here is the smallest honest version of that system as a Docker Compose file. It runs offline. Kafka 4.x runs without ZooKeeper — the cluster-coordination service older Kafka needed — because since Kafka 4.0 (March 2025) the brokers coordinate themselves using a built-in consensus protocol called KRaft; the environment lines below are what that takes. Note that each service gets its own database container: that is the database-per-service rule made visible.

Step-by-step: what docker-compose.yml does, in plain English
  1. Declares one Kafka broker in KRaft mode. KAFKA_PROCESS_ROLES: broker,controller makes this single container both store messages and act as the cluster's coordinator, which is fine for a laptop and never for production.
  2. Three listener lines tell Kafka which port other containers use (kafka:9092) and which port your laptop uses (localhost:29092); mixing these up is the most common "I cannot connect to Kafka" mistake.
  3. KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 lets the internal offsets topic exist with a single broker; production uses 3.
  4. Declares three PostgreSQL 17 containers, one per service, each with its own database name and its own port. No service gets connection details for another service's database.
  5. Declares the three Spring Boot services, each built from its own directory, each told where Kafka is and where its own database is through environment variables read by application.yml.
  6. depends_on with condition: service_healthy waits for each database's health check to pass before starting the service that needs it, so the services do not crash-loop on startup.
docker-compose.ymlruns offline
services:
  kafka:
    image: apache/kafka:4.1.0
    ports:
      - "29092:29092"
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093,HOST://0.0.0.0:29092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,HOST://localhost:29092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT,HOST:PLAINTEXT
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_NUM_PARTITIONS: 6

  orders-db:
    image: postgres:17
    environment:
      POSTGRES_DB: orders
      POSTGRES_USER: orders
      POSTGRES_PASSWORD: orders
    ports: ["5433:5432"]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U orders"]
      interval: 5s
      retries: 10

  payments-db:
    image: postgres:17
    environment:
      POSTGRES_DB: payments
      POSTGRES_USER: payments
      POSTGRES_PASSWORD: payments
    ports: ["5434:5432"]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U payments"]
      interval: 5s
      retries: 10

  inventory-db:
    image: postgres:17
    environment:
      POSTGRES_DB: inventory
      POSTGRES_USER: inventory
      POSTGRES_PASSWORD: inventory
    ports: ["5435:5432"]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U inventory"]
      interval: 5s
      retries: 10

  order-service:
    build: ./order-service
    ports: ["8081:8080"]
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://orders-db:5432/orders
      SPRING_DATASOURCE_USERNAME: orders
      SPRING_DATASOURCE_PASSWORD: orders
      SPRING_KAFKA_BOOTSTRAP_SERVERS: kafka:9092
      PAYMENT_BASE_URL: http://payment-service:8080
    depends_on:
      orders-db: { condition: service_healthy }
      kafka: { condition: service_started }

  payment-service:
    build: ./payment-service
    ports: ["8082:8080"]
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://payments-db:5432/payments
      SPRING_DATASOURCE_USERNAME: payments
      SPRING_DATASOURCE_PASSWORD: payments
      SPRING_KAFKA_BOOTSTRAP_SERVERS: kafka:9092
    depends_on:
      payments-db: { condition: service_healthy }
      kafka: { condition: service_started }

  inventory-service:
    build: ./inventory-service
    ports: ["8083:8080"]
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://inventory-db:5432/inventory
      SPRING_DATASOURCE_USERNAME: inventory
      SPRING_DATASOURCE_PASSWORD: inventory
      SPRING_KAFKA_BOOTSTRAP_SERVERS: kafka:9092
    depends_on:
      inventory-db: { condition: service_healthy }
      kafka: { condition: service_started }

Read what the file says rather than what it does. There are seven containers for three features. Each service can reach Kafka and its own database and nothing else — the order service does not even know the payment database's hostname. That is the point: the wall between services is not a convention, it is the absence of a connection string. When you run docker compose up and everything starts, you have a system where a checkout cannot be a single transaction, and every chapter after this one is about living with that.

Make the invisible visible: who calls whom in the running example, and what each service can reach.

topologyruns offline
client --> order-service ----sync HTTP----> payment-service --> payments-db
              |   \                                  |
              |    +--> orders-db                     +--> Kafka
              +--> Kafka <------ inventory-service --> inventory-db
order-service cannot reach payments-db or inventory-db: no hostname, no credentials

The real costs, priced

Before the decision table, say the costs plainly, because interviewers reward candidates who volunteer them.

Latency: a request that fans out to five services in sequence adds five network round trips; at 2 milliseconds each that is 10 milliseconds, and at the 99th percentile — the slowest one in a hundred — each hop's tail adds up, so the whole request's tail is far worse than any single hop's.

Operational load: twelve services means twelve deploy pipelines, twelve dashboards, twelve on-call rotations or one very tired one, and twelve sets of dependency upgrades when the next Spring Boot major lands.

Data: reports that used to be a JOIN now need either an API call per row or a copied dataset kept in sync by events. Testing: an end-to-end test needs the whole system up, so the test pyramid must shift toward contract tests (section 05).

People: a team of six engineers cannot meaningfully own twelve services; the usual guidance is that a service should have a team, and a team of five to nine can own one to three services well.

Make the invisible visible: the latency cost of fan-out, with worked arithmetic.

fan-out arithmeticruns offline
# illustrative numbers
5 hops in sequence, 2 ms each, median:        5 x 2 ms = 10 ms
each hop is slow (>100 ms) 1 time in 100 (its p99):
  chance that all 5 hops are fast = 0.99^5 = 0.951
  chance that at least one is slow = 1 - 0.951 = 4.9%   <- about 1 request in 20 sees a slow hop

What you see: a request touching five services is slow five times as often as one touching a single service, even though no service got worse.

Choosing the shape — pick the least distributed option that meets the real need
Choose…When…Do not choose it when…
MonolithOne team, or a few teams that already ship together; product still finding its shape; under roughly 20 engineers. Ship fast, refactor freely.Deploys are already blocked on cross-team coordination, or one component's load profile is wrecking the others.
Modular monolithSeveral teams, clear domains, but you want one deploy, one transaction, and one place to debug. Boundaries enforced by build tooling (Spring Modulith, ArchUnit).Teams genuinely need separate release cadences, separate scaling, or separate runtimes; the single database is at its ceiling.
MicroservicesMany teams that must ship independently; parts with very different scaling or availability needs; the organisation can staff platform work (observability, CI/CD, service mesh).The team is small, the domain boundaries are still unclear, or nobody will own the platform. Then the split is a distributed monolith: all the cost, none of the independence.
🧠 Brain power

Before reading on: a team splits a monolith into "user service", "order service", and "product service". Every request to the order service first calls the user service to check the account, then calls the product service to fetch prices. Both calls are synchronous. The user service has a bad deploy and returns errors for four minutes. What does the order service's availability look like during those four minutes, and what does that tell you about where the boundary was cut?

Reveal the answer

The order service's availability drops to zero for the full four minutes, even though nothing about ordering changed.

That is the signature of a boundary cut along a noun rather than a business capability: "user" is not something the order context needs in full, it needs a small, stable fact ("is this account allowed to order?") that could be cached, carried in the request's signed token, or copied into the order service by an event.

When a service cannot do its main job without a synchronous call to another service on every request, the two are not independently deployable — they are a distributed monolith with a network hop in the middle.

The fix is not a retry; it is to redraw the boundary or to change the dependency from a synchronous call to data the order service already holds.

Quick reference — When to split

The only good reason
Independent deployability. If two things must ship together, they are one service wearing two names.
modular monolith
Module boundaries, one deployable. Most of the benefits, none of the network. The right default.
bounded context
The domain-driven design unit a service boundary should follow. Split along how the business talks, not along nouns.
Conway's law
Your architecture ends up shaped like your org chart. Plan teams and services together, or the org wins.
The five costs
Latency (a method call becomes a network call) · operational load · data (no joins, no transactions) · testing · people.

03 · The primerCommunication — Sync, Async, and the Four Tools That Make a Network Call Survivable

Every call between services can be slow, fail, or arrive twice. Four patterns handle that: a timeout on everything, a circuit breaker, a bulkhead, and retries that are safe because the receiver is idempotent.

Here is the incident that every microservice platform eventually has. The recommendation service, a nice-to-have that decorates the checkout page with "you may also like", starts responding in 30 seconds instead of 30 milliseconds because its database is being vacuumed.

The checkout service calls it synchronously with the default HTTP client timeout — which, in many clients, is no timeout at all. Every checkout request thread now sits waiting.

Within ninety seconds all 200 threads of the checkout service's pool are parked on the recommendation call, the checkout service stops answering the API gateway, the gateway's threads fill up, and the entire storefront returns errors.

Revenue goes to zero because a widget that could have been left blank was allowed to hold a thread hostage. Nothing in that chain crashed. The system was brought down by waiting.

Make the invisible visible: the checkout service's thread pool at four moments after the recommendation service slows down.

thread pool occupancyruns offline
# illustrative numbers: pool = 200 threads, about 2 checkouts per second reach the recommendation call
t (s)   stuck on reco call   free threads   what the gateway sees
  0              0               200         200 OK in 40 ms
 30             60               140         200 OK, slower
 60            120                80         first 503s
 90            200                 0         every call times out  ✗

What you see: a thread dump of the checkout service shows the pool parked on one line of code.

thread dump excerptruns offline
# illustrative output
"http-nio-8080-exec-17" #58 RUNNABLE
    at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java)
    at shop.checkout.RecommendationClient.fetch(RecommendationClient.java:41)   <- the widget
    at shop.checkout.CheckoutController.page(CheckoutController.java:77)
... 199 more threads with the same top frames ...

Why: a call with no timeout has no limit on how long it holds a thread, and a thread pool is a fixed resource.

That story contains all four tools of this chapter. A timeout would have freed the thread after, say, 300 milliseconds. A circuit breaker would have noticed that most recent calls were failing and stopped making them for a while, returning an empty widget instantly.

A bulkhead would have capped how many threads the recommendation call may hold at once, so the other 180 threads stayed free for real checkout work.

And a sensible retry policy would have made sure that the "fix" of retrying a slow call three times did not triple the load on the already-drowning service.

Every one of these is a decision about what to do when the other side does not answer — the one situation a local method call never puts you in.

Bridge: what a network call is, one level down

When your code calls paymentClient.charge(order) across the network, four separate things have to succeed: your request has to reach the other machine, that machine has to process it, the reply has to travel back, and your side has to still be listening.

Any of the four can fail independently, and the cruel part is that from your side, three of the failures look identical. If the request was lost, the reply was lost, or the server is simply slow, all you see is silence.

So you never know whether the payment happened. This is the fundamental fact of distributed systems — the Distributed Systems primer covers it as the two-generals problem — and it is why "just retry" is dangerous: a retry after a lost reply charges the card twice.

The only safe retry is one the receiver can recognise as a repeat, which is what idempotency means: performing the same request more than once has the same effect as performing it once.

In practice the caller attaches a unique idempotency key (a UUID generated once per logical operation), the receiver stores the key with the result, and a repeated key returns the stored result instead of doing the work again.

Stripe's payments API works exactly this way with an Idempotency-Key header, and it is the reason a client can retry a charge safely.

Make the invisible visible: the same charge, retried after a lost reply, without and with an idempotency key.

sequence pictureruns offline
Order service            Payment service              payments table
POST /charge  ------->
                         charge card  ✓               p-1  o-1  CHARGED
             X<-------   200 OK (reply lost)
timeout after 800 ms  ✗  (outcome unknown to the caller)
retry POST /charge --->  charge card again  ✗          p-2  o-1  CHARGED   <- double charge

What you see now: with an idempotency key the second request is recognised and the stored result is returned.

sequence pictureruns offline
Order service                  Payment service                  payments / idempotency_keys
POST /charge  Idempotency-Key: o-1 -->
                               key o-1 unseen: charge ✓       p-1 o-1 CHARGED | key o-1 -> p-1
             X<-----------     200 OK (reply lost)
retry POST /charge, same key -->
                               key o-1 found: no charge  ✓    (still one row)   returns p-1

The fix: the receiver stores the key with the result, and a unique constraint on the key makes two concurrent copies safe.

PaymentController.java (receiving side)runs offline
@PostMapping("/payments")
ResponseEntity<ChargeResult> charge(@RequestHeader("Idempotency-Key") String key,
                                    @RequestBody ChargeRequest req) {
    // ✅ FIX: same key -> same stored result, the card is charged once
    // (a UNIQUE constraint on key makes a concurrent duplicate fail instead of charging)
    ChargeResult result = store.findByKey(key)
            .orElseGet(() -> store.save(key, cardProcessor.charge(req)));
    return ResponseEntity.ok(result);
}

Synchronous or asynchronous: the real difference

A synchronous call — REST over HTTP, or gRPC, which is a binary remote-procedure-call protocol from Google that runs over HTTP/2 and uses Protocol Buffers for compact typed messages — means the caller waits for the answer and cannot finish its own work without it.

An asynchronous message — published to a broker such as Apache Kafka or RabbitMQ — means the caller writes the message somewhere durable, gets an acknowledgement that the message was stored, and moves on; whoever needs to act on it reads it later.

The difference is not speed. The difference is coupling in time.

With a synchronous call, both services must be up and fast at the same moment, and the caller's availability is the product of every callee's availability: three dependencies at 99.9% each give you at best 99.7%.

With a message, the consumer can be down for ten minutes and the messages wait in the broker; the caller never noticed.

The price is that the caller does not get an answer, so the design has to be shaped around "I have recorded your request" rather than "here is your result".

Make the invisible visible: the availability arithmetic, and a consumer that is down while messages wait.

worked arithmeticruns offline
three synchronous dependencies at 99.9% each:  0.999 x 0.999 x 0.999 = 0.997  -> at best 99.7%
downtime per 30 days (43,200 min):   one 99.9% service  = 43 min     the chain of three = about 130 min
async: broker stores the message, caller continues -> the caller's availability does not include the consumer's
message timelineruns offline
# illustrative output: topic orders, partition 0
offset 100  OrderPlaced o-1   consumer payment: processed ✓
10:00  payment-service goes down
offset 101  OrderPlaced o-2   waiting in the broker
offset 102  OrderPlaced o-3   waiting in the broker      checkout still answers in ~5 ms ✓
10:10  payment-service back   reads 101, 102 in order    nobody noticed  ✓

Kafka and RabbitMQ solve different problems and interviewers like to hear you say so. RabbitMQ is a message queue: a message is delivered to one consumer and then deleted, with rich routing rules.

Kafka is a distributed log: messages are appended to a partitioned, ordered file that is kept for days, and consumers keep their own position (the offset) in it, so many consumer groups can read the same stream independently and a new consumer can replay history.

Kafka is the default for event streams that several services care about; RabbitMQ (or a cloud queue such as SQS) is the default for work queues where each job must be done once by one worker.

Kafka ordering holds only within a partition, and the partition is chosen by the message key, so "all events for order 123 in order" means "key every event by the order id".

Make the invisible visible: which partition each event lands in when the key is the order id, and when it is not.

partitions and keysruns offline
# illustrative: topic orders, 6 partitions, partition = hash(key) mod 6
key = orderId  : o-123 Created -> p4 | o-123 Paid -> p4 | o-123 Shipped -> p4     order kept ✓
no key (round-robin): o-123 Created -> p4 | o-123 Paid -> p1 | o-123 Shipped -> p5
    consumer on p5 may read Shipped before Paid arrives from p1                   ✗ out of order
Synchronous: caller waits for every hop Asynchronous: caller waits only for the broker checkout payment fraud check call call checkout thread held for the whole chain — 30 s if fraud check is slow availability ≈ product of all three · latency = sum of all three needs: timeout · retry with jitter · breaker · bulkhead checkout Kafka orders topic payment fraud check append each reads at its own pace held ~5 ms consumer down 10 min? messages wait · caller never noticed price: no answer in the reply · at-least-once · ordering per key only The choice is about coupling in time: must both sides be up and fast at the same instant? Use sync when the caller cannot proceed without the answer; use async when it can record and move on.
Fig. E7.2 — The same three services, called synchronously and asynchronously. The highlighted bar is the resource that a slow dependency consumes in the synchronous shape: the caller's own thread, for the whole chain.

The four tools, mechanism by mechanism

Each of the four tools is its own pattern: a timeout, retries with backoff, a circuit breaker and a bulkhead. They are listed here in the order a failing call meets them. (The fourth tool in the idea list, idempotency, is what makes retries safe, as the lost-reply picture above showed.)

Pattern: Timeout

A timeout is a limit on how long a call may wait before the caller gives up and frees its thread.

The problem: without a timeout, one stalled payment call holds a checkout thread for as long as the payment service stays stalled.

sequence pictureruns offline
Order thread         Payment service
POST /charge ------->  (stalled: its database is vacuuming)
  waiting ...  5 s     waiting
  waiting ... 30 s     still no reply     the thread is gone from the pool for 30 s+  ✗
  100 such calls -> 100 of 200 threads gone

How it works: you need two kinds, and a deadline across the chain.

  1. Connect timeout: bounds how long you wait to open the socket.
  2. Read (or response) timeout: bounds how long you wait for the reply once connected. Set it from the callee's measured 99th-percentile latency plus a margin, not from a guess: if payment normally answers in 80 milliseconds at p99, a 500-millisecond timeout catches a stuck call without cutting off healthy slow ones.
  3. Deadline: the very first service in the chain decides "this request has 2 seconds total", and each hop passes the remaining budget along (gRPC does this natively with deadline propagation; over REST you carry a header), so a downstream call never waits longer than the user would.
deadline budgetruns offline
# illustrative: the header name is up to your team
request arrives with a 2000 ms budget
checkout   spent  40 ms -> calls payment with remaining = 1960 ms
payment    spent 900 ms -> calls fraud   with remaining = 1060 ms
fraud      sees remaining 1060 ms: never waits longer than that  ✓

The setup: two lines of configuration on the HTTP client (the full file is further down).

application.yml (excerpt)runs offline
spring:
  http:
    client:
      connect-timeout: 300ms
      read-timeout: 800ms

What you see: the same stall, without and with the read timeout.

consoleruns offline
# illustrative output
without:  POST /payments ... still waiting after 30000 ms (thread http-nio-8080-exec-17)     ✗
with:     POST /payments -> ResourceAccessException: I/O error ... Read timed out  after 800 ms   ✓ thread freed

The trap: a timeout that is wrong in either direction, and a timeout that hides what happened.

When to use it / when not: every network call gets one.

Pattern: Retry with Backoff and Jitter

A retry repeats a failed call, and exponential backoff with jitter spaces the repeats out so they do not arrive together.

The problem: retries help with a blip and hurt with an outage. A thousand clients fail at the same instant and retry at the same instant.

retry stormruns offline
# illustrative: 1000 clients fail at t = 0, wait 100, 200, 400 ms, no jitter
t = 0.1 s   ################  1000 retries hit the recovering service at once
t = 0.3 s   ################  1000 again
t = 0.7 s   ################  1000 again    ✗ it falls over each time it starts to recover

How it works: three conditions make a retry safe, and backoff plus jitter keep it gentle.

  1. The operation is idempotent: a repeat has the same effect as one call.
  2. The failure is retryable: a connection reset or a 503 can be fixed by trying again; a 400 or a 404 cannot.
  3. The retry adds no load to a drowning service: this is where backoff and jitter come in.
  4. Backoff: each retry waits longer than the last (100 ms, 200 ms, 400 ms).
  5. Jitter: a random amount is added to each wait, so the wave spreads out.
  6. A cap: three attempts is plenty.
with jitterruns offline
# illustrative: same 1000 clients, waits randomised by +/- 50%
first retry between 50 and 150 ms:   about 10 retries per millisecond, spread  ✓
second retry between 100 and 300 ms: spread again                              ✓  the service sees a slope, not a wall

The setup: three attempts, 200 ms doubling, 50% jitter, and only for failures a retry can fix (the full file is further down).

application.yml (excerpt)runs offline
resilience4j:
  retry:
    instances:
      payment:
        max-attempts: 3
        wait-duration: 200ms
        enable-exponential-backoff: true
        exponential-backoff-multiplier: 2
        enable-randomized-wait: true
        randomized-wait-factor: 0.5

What you see: the log of one call that needed retries.

consoleruns offline
# illustrative output
attempt 1  POST /payments  503   (wait about 200 ms, between 100 and 300)
attempt 2  POST /payments  503   (wait about 400 ms, between 200 and 600)
attempt 3  POST /payments  200   ✓

The trap: retry amplification. Retrying at every layer multiplies, and it is the same arithmetic as the Brain power question below.

amplificationruns offline
# 5 services in a chain, each retries 3 times; the last one is failing
layer 1 calls layer 2:   1 call
layer 2 calls layer 3:   3 calls
layer 3 calls layer 4:   9 calls
layer 4 calls layer 5:  27 calls
layer 5 receives:       81 calls for one user click   ✗   (ten attempts across five layers = 10^5 = 100,000)

Cap the total: ten attempts across five layers of services multiplies into a hundred thousand calls for one user click, which is sometimes called retry amplification.

When to use it / when not: retry transient faults at one layer only.

Pattern: Circuit Breaker

A circuit breaker is a small state machine wrapped around a call, named after the electrical part that cuts power when the current is dangerous.

The problem: timeouts alone still make every caller wait the full timeout on a dependency that is down.

capacity pictureruns offline
# illustrative: payment is down, order-service makes 100 payment calls per second, read timeout 800 ms
without breaker: 100 calls/s x 0.8 s = 80 threads parked on payment, all the time; each customer waits 800 ms  ✗
with breaker OPEN: 0 threads on payment; fallback answers in microseconds                                    ✓

How it works: three states.

  1. Closed: calls flow through while the failure rate over a sliding window stays under a threshold — say, fewer than 50% of the last 20 calls failed or exceeded a slow-call limit.
  2. Open: when the rate crosses the threshold, for a wait period every call fails immediately with a CallNotPermittedException without touching the network, and your code returns a fallback (an empty widget, a cached price, a "try again shortly").
  3. Half-open: after the wait it lets a few trial calls through, and closes again if they succeed.

The point is not to protect the caller from errors; it is to stop hammering a struggling dependency and to fail fast so your own threads stay free.

state machine over timeruns offline
# using the settings in application.yml: window 20, minimum 10 calls, 50% threshold, open 10 s, 3 trial calls
calls 1-9    9 failures      CLOSED   fewer than 10 calls recorded: no decision yet
call 10      10 of 10 failed CLOSED -> OPEN   (100% >= 50%)
next 10 s    every call      OPEN     CallNotPermittedException -> fallbackCharge, no network
after 10 s                   OPEN -> HALF_OPEN   3 trial calls allowed
trial 3/3 ok                 HALF_OPEN -> CLOSED   ✓      (2 of 3 failing would send it back to OPEN ✗)

The setup: Resilience4j is the standard Java library for this, and Spring Boot 3.5+ and 4.x integrate it through the resilience4j-spring-boot3 starter. The circuitbreaker block of application.yml and the annotation in PaymentGateway below are the whole setup.

What you see: the breaker's state is visible on the actuator endpoint.

/actuator/circuitbreakersruns offline
{
  "circuitBreakers": {
    "payment": {
      "state": "OPEN",
      "failureRate": "100.0%",
      "failureRateThreshold": "50.0%",
      "bufferedCalls": 10,
      "failedCalls": 10,
      "notPermittedCalls": 42
    }
  }
}

The trap: three ways a breaker itself goes wrong.

When to use it / when not: put one around every synchronous call to a dependency that can fail slowly.

Pattern: Bulkhead

A bulkhead is a cap on concurrency, named after the watertight walls in a ship's hull that stop one flooded compartment from sinking the vessel.

The problem: one pool of 200 threads serves everything, so a slow recommendation call can use all of them and the real checkout work has none left.

shared poolruns offline
# illustrative: one pool of 200 threads
moment      recommendation   payment   free
healthy          5              30      165
reco slow      150              30       20
reco slower    170              30        0   ✗ payment cannot get a thread either

How it works:

  1. Give each dependency a cap: a semaphore bulkhead of 20 on the recommendation call means at most 20 threads may be inside that call at once.
  2. Reject the rest instantly: the 21st caller fails immediately rather than waiting.
  3. Set the cap from the arithmetic: if you want the recommendation dependency to consume at most 10% of a 200-thread pool, the bulkhead is 20.

Bulkheads are what keep a slow non-critical dependency from starving critical work, which is exactly the failure in the opening story.

with a bulkhead of 20runs offline
moment      recommendation   payment   free
healthy          5              30      165
reco slow       20              30      150
reco slower     20 (rest rejected)  30  150   ✓ checkout keeps its threads

The setup: one block in the config, one annotation on the method (both in the full code below).

application.yml (excerpt)runs offline
resilience4j:
  bulkhead:
    instances:
      payment:
        max-concurrent-calls: 25
        max-wait-duration: 0

What you see: the 26th concurrent call is refused at once.

consoleruns offline
# illustrative output
call 26  BulkheadFullException (the bulkhead is full)  after 0 ms  -> fallbackCharge -> PENDING   ✓
without a bulkhead: call 26 waits for a thread that never comes                                    ✗

The trap: a bulkhead that is not separate from the thing it protects.

When to use it / when not: use one per dependency, sized from the share of the pool you can afford to lose.

The code: an order service that survives a bad payment service

This is a complete Spring Boot service that calls the payment service through Resilience4j with all four tools attached, and an idempotency key on the outbound call. It compiles against Spring Boot 3.5.x or 4.x with Java 21 (as of Aug 2026: Spring Boot 4.0 shipped in November 2025 on Spring Framework 7 and requires Java 17+, and the 3.5 line remains in open-source support until mid-2026; Resilience4j 2.3.x supports both). The client is Spring's RestClient, the synchronous successor to RestTemplate.

Step-by-step: what PaymentGateway.java and application.yml do, in plain English
  1. application.yml sets connect and read timeouts on the HTTP client factory, so no payment call may hold a thread for more than 800 ms after connecting.
  2. The resilience4j.circuitbreaker block defines an instance called payment: a sliding window of the last 20 calls, open when 50% failed or 50% were slower than 600 ms, stay open 10 s, then let 3 trial calls through in half-open.
  3. The resilience4j.retry block allows 3 attempts with an initial wait of 200 ms, doubling each time, with randomised jitter of up to 50% — and only for the exception types listed, so a 4xx response is never retried.
  4. The resilience4j.bulkhead block caps concurrent payment calls at 25 with zero wait, so the 26th caller fails immediately instead of queueing.
  5. RestClientConfig builds a RestClient bean with those timeouts and the payment base URL from the environment.
  6. PaymentGateway.charge(...) is annotated with all three Resilience4j aspects. The annotation order in Resilience4j's default is Retry outside CircuitBreaker outside Bulkhead: the bulkhead admits the call, the breaker decides whether to attempt it, and the retry repeats the whole thing on a retryable failure.
  7. The method sends the Idempotency-Key header set to the order id, so if a retry fires after a lost reply, the payment service recognises the repeat and returns the original result instead of charging again.
  8. The fallbackCharge method has the same parameters plus a Throwable. When the breaker is open or all retries are exhausted, Resilience4j calls it instead of throwing, and it returns a PENDING result so the order can be recorded and completed later by an event rather than failing the customer.
  9. OrderController shows the effect: it creates the order, calls the gateway, and returns 202 Accepted when payment is pending, 201 Created when it succeeded — the HTTP status tells the client honestly what happened.
order-service/src/main/resources/application.ymlruns offline
spring:
  application:
    name: order-service
  http:
    client:
      connect-timeout: 300ms
      read-timeout: 800ms

payment:
  base-url: ${PAYMENT_BASE_URL:http://localhost:8082}

resilience4j:
  circuitbreaker:
    instances:
      payment:
        sliding-window-type: COUNT_BASED
        sliding-window-size: 20
        minimum-number-of-calls: 10
        failure-rate-threshold: 50
        slow-call-duration-threshold: 600ms
        slow-call-rate-threshold: 50
        wait-duration-in-open-state: 10s
        permitted-number-of-calls-in-half-open-state: 3
        automatic-transition-from-open-to-half-open-enabled: true
        record-exceptions:
          - org.springframework.web.client.ResourceAccessException
          - org.springframework.web.client.HttpServerErrorException
        ignore-exceptions:
          - org.springframework.web.client.HttpClientErrorException
  retry:
    instances:
      payment:
        max-attempts: 3
        wait-duration: 200ms
        enable-exponential-backoff: true
        exponential-backoff-multiplier: 2
        enable-randomized-wait: true
        randomized-wait-factor: 0.5
        retry-exceptions:
          - org.springframework.web.client.ResourceAccessException
          - org.springframework.web.client.HttpServerErrorException
        ignore-exceptions:
          - org.springframework.web.client.HttpClientErrorException
  bulkhead:
    instances:
      payment:
        max-concurrent-calls: 25
        max-wait-duration: 0

management:
  endpoints:
    web:
      exposure:
        include: health,metrics,circuitbreakers,prometheus
  health:
    circuitbreakers:
      enabled: true
order-service/src/main/java/shop/orders/PaymentGateway.javaruns offline
package shop.orders;

// build.gradle.kts dependencies (Spring Boot 3.5+/4.x, Java 21):
//   implementation("org.springframework.boot:spring-boot-starter-web")
//   implementation("org.springframework.boot:spring-boot-starter-actuator")
//   implementation("io.github.resilience4j:resilience4j-spring-boot3:2.3.0")
//   implementation("org.springframework.boot:spring-boot-starter-aop")

import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;

import java.math.BigDecimal;
import java.util.UUID;

record ChargeRequest(String orderId, BigDecimal amount, String currency) {}
record ChargeResult(String status, String paymentId) {}
record CheckoutRequest(BigDecimal amount, String currency) {}
record CheckoutResponse(String orderId, String paymentStatus) {}

@Configuration
class RestClientConfig {
    @Bean
    RestClient paymentRestClient(RestClient.Builder builder,
                                 @Value("${payment.base-url}") String baseUrl) {
        // The builder already carries the connect/read timeouts from application.yml
        // (spring.http.client.*). We only pin the base URL here.
        return builder.baseUrl(baseUrl).build();
    }
}

@Service
public class PaymentGateway {

    private final RestClient client;

    PaymentGateway(RestClient paymentRestClient) {
        this.client = paymentRestClient;
    }

    // Resilience4j default aspect order: Retry(CircuitBreaker(Bulkhead(call))).
    // The bulkhead admits at most 25 concurrent calls; the breaker refuses calls
    // while open; the retry re-runs the whole thing on a retryable exception.
    @Bulkhead(name = "payment", fallbackMethod = "fallbackCharge")
    @CircuitBreaker(name = "payment", fallbackMethod = "fallbackCharge")
    @Retry(name = "payment", fallbackMethod = "fallbackCharge")
    public ChargeResult charge(String orderId, BigDecimal amount, String currency) {
        return client.post()
                .uri("/payments")
                // The order id is the idempotency key: a retry after a lost reply
                // makes the payment service return the first result, not charge twice.
                .header("Idempotency-Key", orderId)
                .body(new ChargeRequest(orderId, amount, currency))
                .retrieve()
                .body(ChargeResult.class);
    }

    // Same signature plus Throwable. Called when the breaker is open, the bulkhead
    // is full, or every retry attempt failed. We do NOT pretend the charge worked:
    // PENDING tells the caller to record the order and finish payment asynchronously.
    ChargeResult fallbackCharge(String orderId, BigDecimal amount, String currency, Throwable cause) {
        return new ChargeResult("PENDING", null);
    }
}

@RestController
class OrderController {

    private final PaymentGateway payments;

    OrderController(PaymentGateway payments) {
        this.payments = payments;
    }

    @PostMapping("/orders")
    ResponseEntity<CheckoutResponse> checkout(@RequestBody CheckoutRequest req) {
        String orderId = UUID.randomUUID().toString();
        ChargeResult result = payments.charge(orderId, req.amount(), req.currency());
        HttpStatus status = "PENDING".equals(result.status())
                ? HttpStatus.ACCEPTED   // 202: recorded, payment will complete later
                : HttpStatus.CREATED;   // 201: paid now
        return ResponseEntity.status(status)
                .body(new CheckoutResponse(orderId, result.status()));
    }
}

What you see: the order service while the payment service goes bad, step by step.

  1. Calls 1-10: they fail or take longer than 600 ms; the breaker's window fills and the failure rate crosses 50%.
  2. From the eleventh call on: charge() does not touch the network at all. Resilience4j throws CallNotPermittedException internally and routes straight to fallbackCharge, which answers in microseconds.
  3. Meanwhile: threads in the order service stay free, the gateway stays healthy, and customers see "order received, payment processing" instead of a spinner followed by an error.
  4. Ten seconds later: three trial calls go through; if payment has recovered, the breaker closes and normal flow resumes.
  5. All along: every call carries the order id as its idempotency key, so the retries that happened before the breaker opened could not have double-charged anyone.
consoleruns offline
# illustrative output
14:02:01  POST /orders -> 201 Created   payment 240 ms
14:02:09  POST /orders -> 202 Accepted  payment retried 3 times, then fallback PENDING  
14:02:11  breaker payment: CLOSED -> OPEN        (failure rate 100.0%)
14:02:12  POST /orders -> 202 Accepted  payment fallback PENDING in 1 ms
14:02:21  breaker payment: OPEN -> HALF_OPEN
14:02:22  breaker payment: HALF_OPEN -> CLOSED   3 of 3 trial calls ok
          POST /orders -> 201 Created

You can watch the breaker's state at /actuator/circuitbreakers, and the resilience4j_circuitbreaker_state metric is the one to alert on.

Finding each other: discovery, gateways, and the mesh

Three more pieces of plumbing sit around every call, and interviews expect you to place each one correctly: service discovery (where is the callee), the API gateway (the front door), and the service mesh (traffic between services).

Pattern: Service Discovery

Service discovery answers "where is the payment service right now?" when instances start and stop constantly.

The problem: a caller with a hard-coded address breaks at the next rollout, because new pods get new IPs.

pod addresses over a rolloutruns offline
# illustrative
before rollout:   payment pods 10.1.4.7  10.1.5.2  10.1.6.9      order-service has "10.1.4.7" in config
after rollout:    payment pods 10.1.4.21 10.1.5.30 10.1.6.12
order-service -> 10.1.4.7   Connection refused   ✗

How it works: in Kubernetes the answer is built in.

  1. A Service object gives a stable DNS name (payment-service).
  2. Its selector finds the pods by label.
  3. Only ready pods are listed as endpoints, and the Service load-balances across them.
  4. Callers use the name, never an IP.

This is why client-side registries such as Eureka are much less common than they were in 2018.

The setup: one Service object.

payment-service.yamlruns offline
apiVersion: v1
kind: Service
metadata:
  name: payment-service
spec:
  selector:
    app: payment-service
  ports:
    - port: 8080
      targetPort: 8080

What you see: the endpoints behind the name, before and after a rollout.

kubectlruns offline
# illustrative output
$ kubectl get endpoints payment-service
NAME              ENDPOINTS                                   AGE
payment-service   10.1.4.7:8080,10.1.5.2:8080,10.1.6.9:8080   3d
(after rollout)   10.1.4.21:8080,10.1.5.30:8080,10.1.6.12:8080  ✓ same name, new addresses

The trap: balancing happens per connection, not per request. One long-lived HTTP/2 or gRPC connection sticks to one pod.

one connection, one podruns offline
# illustrative: 300 requests/s over a single long-lived connection
payment pod A   300 req/s   ✗
payment pod B     0 req/s
payment pod C     0 req/s   <- scale-out did not help; needs client-side or mesh balancing per request

When to use it / when not: every service-to-service call needs some form of discovery.

Pattern: API Gateway

An API gateway (Spring Cloud Gateway, Kong, Envoy, a cloud load balancer) is the single front door for outside traffic.

The problem: without it every client must know every service address, and every service must implement TLS, authentication and rate limits.

no front doorruns offline
mobile app --> order-service      (own login check, own TLS, own limits)
          --> payment-service    (own login check, own TLS, own limits)
          --> inventory-service  (own login check, own TLS, own limits)   ✗ three copies, three ways to be wrong

How it works: the gateway does four jobs, so no internal service has to be reachable from the internet.

  1. Terminates TLS.
  2. Authenticates the caller.
  3. Applies rate limits.
  4. Routes to the internal service.

The setup: two routes in the Spring Cloud Gateway Java DSL.

GatewayRoutes.javaruns offline
@Bean
RouteLocator routes(RouteLocatorBuilder b) {
    return b.routes()
        .route("orders",   r -> r.path("/api/orders/**").uri("http://order-service:8080"))
        .route("payments", r -> r.path("/api/payments/**").uri("http://payment-service:8080"))
        .build();
}

What you see: the same request from outside, with and without the front door.

curlruns offline
# illustrative output
$ curl -i https://shop.example.com/api/orders/42            (no token)
HTTP/1.1 401 Unauthorized                                    ✓ rejected at the gateway, order-service never saw it
$ curl -i http://payment-service:8080/payments               (from the internet)
curl: (6) Could not resolve host                             ✓ not reachable from outside

The trap: the gateway turning into a new monolith.

When to use it / when not: use it for the edge, not for the inside.

Pattern: Backend for Frontend (BFF)

A Backend for Frontend is a small gateway-side service built for one kind of client (web, mobile), owned by that client's team, that shapes responses to what that client needs.

The problem: one general order API returns thirty fields and needs three calls to build a screen, which is wasteful on a phone.

payload sizesruns offline
# illustrative
web order page:    needs 30 fields from orders + payment + shipping   (3 calls, 9 KB)
mobile summary:    needs id, total, payment status                    (same 3 calls, same 9 KB)  ✗ phone downloads 6x more than it shows

How it works:

  1. One BFF per client type: a web BFF and a mobile BFF.
  2. The BFF calls the services it needs, often in parallel, and builds exactly one response for its client.
  3. The client team owns it and changes it without asking the service teams.

The setup: a mobile endpoint that returns only what the screen shows.

MobileOrderController.javaruns offline
record MobileOrder(String id, java.math.BigDecimal total, String paymentStatus) {}

@GetMapping("/mobile/orders/{id}")
MobileOrder summary(@PathVariable String id) {
    var order = orders.get(id);                 // call to order-service
    var payment = payments.statusOf(id);        // call to payment-service
    return new MobileOrder(order.id(), order.total(), payment.status());   // ✅ FIX: 3 fields, not 30
}

What you see: the same screen, before and after.

payload sizesruns offline
# illustrative output
before (general API):  3 client calls, 9 KB
after  (mobile BFF):  1 client call,   0.2 KB   ✓

The trap: copying business rules into each BFF. The rules then drift apart, so keep them in the services and let the BFF only shape and combine.

When to use it / when not: use it when client types need clearly different data shapes.

Pattern: Sidecar and Service Mesh

A service mesh (Istio or Linkerd, both current as of 2026) handles the traffic between services by putting a small proxy beside each pod — a sidecar — or, in Istio's newer ambient mode, a per-node proxy.

The problem: twelve services in three languages each implement mutual TLS, retries and metrics, and each does it a little differently.

per-service plumbingruns offline
order-service (Java)       own mTLS setup, own retry library, own metrics names
payment-service (Java)     own mTLS setup, different retry settings
shipping-service (Go)      own mTLS setup, no retries at all    ✗ three behaviours for one rule

How it works: the mesh then does mutual TLS between services, retries, timeouts, and traffic splitting for canaries, without any of that being in your Java code.

  1. A proxy sits beside each pod (the sidecar) and intercepts its traffic.
  2. Proxies talk to each other over mutual TLS.
  3. A control plane pushes the rules (timeouts, retries, traffic splits) to every proxy.
pod with a sidecarruns offline
pod payment-service
  [ app container :8080 ] <--localhost--> [ sidecar proxy ] <==mTLS==> sidecar of order-service pod
                                              ^ rules from the control plane

The setup: one Istio VirtualService with a timeout and retries for the payment service.

payment-virtualservice.yamlruns offline
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: payment-service
spec:
  hosts: [payment-service]
  http:
    - route:
        - destination: { host: payment-service }
      timeout: 1s
      retries:
        attempts: 2            # retries after the first try
        perTryTimeout: 500ms
        retryOn: 5xx,connect-failure

What you see: what a double configuration does to the payment service.

retry arithmeticruns offline
# the application retries 3 attempts; the mesh adds up to 2 retries (3 tries) under each one
one order click -> app attempt 1,2,3 -> each makes up to 3 mesh tries -> up to 9 calls to payment   ✗ you configured "3", you got 9

The trade: another layer to run, a few milliseconds of latency per hop, and the fact that mesh-level retries and library-level retries multiply if you configure both without noticing.

The trap: retries in both places, as the picture shows. Pick one layer for retries.

When to use it / when not: a mesh pays for itself with many services and a platform team.

Choosing the communication style for a given interaction
Choose…When…Watch out for…
Synchronous RESTThe caller needs the answer to continue (price lookup, authorisation); the call is fast and the dependency is critical anyway; humans and third parties will read the API.Availability multiplies down; every call needs timeout + breaker + bulkhead; JSON over HTTP/1.1 is the slowest wire format.
Synchronous gRPCInternal service-to-service calls that are chatty or latency-sensitive; you want typed contracts, streaming, and deadline propagation for free.Browsers need a proxy; debugging binary payloads is harder; still synchronous, so the same failure math applies.
Async event (Kafka)Something happened that several services care about ("order placed"); consumers may be slow or down; you want replay and audit.At-least-once delivery means consumers must be idempotent; ordering only per key; the producer never learns whether the consumer succeeded.
Async command (queue)Work that must be done once by one worker, possibly later (send email, generate PDF); natural retries and dead-letter queues.Poison messages loop forever without a dead-letter queue; visibility timeouts must exceed processing time or jobs run twice.
🧠 Brain power

Before reading on: five services form a chain, and each one is configured to retry a failed call three times. The last service in the chain fails every request for one minute. For one user request that enters the top of the chain, how many calls does the last service receive? And what single change stops the explosion without removing retries entirely?

Reveal the answer

Each layer multiplies by three.

The first service tries three times; for each of those, the second tries three times; and so on through four hops of retrying, so the last service receives 3 × 3 × 3 × 3 = 81 calls for one user click — and with ten thousand users clicking, 810,000 calls against a service that is already failing.

The fix is a retry budget: retry only at one layer (usually the edge, or the layer closest to the failure, but not both), cap retries as a percentage of normal traffic (a common budget is "retries may add at most 10% extra load"), and let the circuit breaker turn retries off entirely once the failure rate is high.

The rule of thumb to say aloud: retries are for transient failures lasting milliseconds, and a breaker is for failures lasting seconds or longer.

Quick reference — Communication

timeout
On every call, always. A call without a timeout is a thread you have given away permanently.
circuit breaker
After N failures, stop calling and fail fast. Protects the caller, and gives the callee room to recover.
bulkhead
Separate pools per dependency, so one slow downstream cannot consume every thread.
Retries
Exponential backoff with jitter. Without jitter every client retries in lockstep, and you get a retry storm.
idempotency key
What makes a retry safe. The receiver stores the key and replays the original response.
Queue vs log
A queue delivers and removes. A log keeps messages and each consumer tracks its own offset — which is what lets you replay.

04 · The primerData — One Database Per Service, Sagas, and the Outbox

One database per service means you cannot use a transaction across services. What replaces it is a saga with compensating actions, and an outbox so your database write and your message never disagree.

Start with the failure that this chapter exists to prevent. A checkout does three things: it inserts an order row, it charges the card, and it reserves stock.

In the monolith those were one transaction: three statements, one COMMIT, and if the stock reservation failed, the order and the charge were rolled back by the database, for free, with no code.

In the split system they are three services with three databases, and there is no COMMIT that spans them. So consider what happens on a Tuesday afternoon when the order service writes its row, calls payment (card charged, $340), and then the inventory service times out.

The order exists. The money is gone. No stock is reserved. Nothing crashed; the system simply stopped half-way through a business operation, and unless somebody designed for exactly that moment, the customer will be charged for goods that never ship.

Every pattern in this chapter is a way to make "stopped half-way" either impossible to observe or safe to recover from.

Why each service owns its database

The database-per-service rule says that only one service may read or write a given set of tables, and every other service gets that data through the owning service's API or events. The reason is not purity.

It is that a shared database is a hidden, untyped, unversioned API: the moment two services read the same table, neither can change that table's schema without breaking the other, and you are back to coordinated deploys — a distributed monolith.

The rule has a hard consequence you must say aloud in interviews: there is no cross-service transaction. A JOIN between orders and customers becomes either a call or a local copy.

And that leads to the two big questions of the chapter: how does a multi-step business operation stay correct without a shared transaction (sagas), and how does a service reliably tell the others what it did (the outbox)?

Pattern: Database per service

The problem: Two services share one database, and the order team renames a column. Nothing in either service's code says that the other one reads it.

sequence: shared databaseruns offline
shared-db (one schema)
  orders(id, status, amount)
     ▲ writes               ▲ SELECT status          ▲ SELECT status
order-service        reporting-service         payment-service

10:02  order team deploys:  ALTER TABLE orders RENAME COLUMN status TO state;   ✓ order-service
10:02  reporting-service runs its nightly query                                 ✗ breaks
10:02  payment-service checks order status before charging                      ✗ breaks

How it works: Every table has exactly one owning service, and everyone else goes through that service.

  1. Own: each service gets its own database (or its own schema with its own credentials) holding only its tables.
  2. Expose: other services reach the data through the owner's API or through events the owner publishes.
  3. Copy: a service that needs another service's data often, keeps a small local copy fed by events, instead of a cross-service JOIN.
table ownershipruns offline
service            owns (tables)                      may read
order-service      orders, outbox                     its own tables only
payment-service    payments, processed_events         its own tables only
inventory-service  stock, processed_events, outbox    its own tables only

The orders page needs the customer's name (a JOIN in the monolith):
  option A  call customer-service  GET /customers/42     always fresh, one more hop
  option B  keep order_customer(customer_id, name)       fast, a little stale,
            updated by CustomerRenamed events            works when customer-service is down

The setup: The wall is enforced by the database, not by good intentions: one role per service, one schema per role.

V1__roles.sql (run by the platform team)runs offline
CREATE ROLE order_svc     LOGIN PASSWORD 'change-me';
CREATE ROLE inventory_svc LOGIN PASSWORD 'change-me';

CREATE SCHEMA orders    AUTHORIZATION order_svc;
CREATE SCHEMA inventory AUTHORIZATION inventory_svc;
-- ✅ FIX: each role owns its schema and was granted nothing on the other one

What you see: The same cross-service read, first against the shared schema, then against the walled one.

without the patternruns offline
# illustrative output
10:02:07 reporting-service  ERROR: column "status" does not exist
10:02:09 payment-service    ERROR: column "status" does not exist
10:02:15 pager: 2 services failing right after the order-service deploy
with the patternruns offline
# illustrative output
-- connected as inventory_svc
SELECT status FROM orders.orders;
ERROR:  permission denied for schema orders
-- the read fails at design time, in a developer's terminal, not in production

The trap: Separate schemas on paper, but every service connects with the same admin account, so a "quick" cross-schema JOIN works and quietly becomes a dependency.

the wall that is not thereruns offline
# illustrative output
-- connected as shared_admin (used by all services)
SELECT o.id, s.available FROM orders.orders o JOIN inventory.stock s ON s.sku = o.sku;
 id   | available
 7c1e | 8              -- ✗ works today; inventory can never change stock's columns freely again

When to use it / when not: It pays off when teams deploy independently; it costs you joins and transactions.

Bridge: you already know what a saga is — it is a compensating transaction

Think of how a travel agent books a trip: flight, then hotel, then car. If the car rental fails, the agent does not "roll back" the flight; the flight was really booked.

The agent cancels it — a new action that undoes the effect of the first.

A saga is exactly that: a business operation made of a sequence of local transactions, one per service, where each step has a compensating action that reverses it if a later step fails.

Order created → payment charged → stock reserved; on failure at stock, run "refund payment" and "cancel order".

The word to stress is reverses, not rolls back: the charge was committed and visible, the refund is another committed, visible event, and for a while the customer's statement will show both.

Sagas trade the atomicity of one transaction for the availability of many, and they accept that the system passes through intermediate states other people can see. That is eventual consistency in one sentence: every service will agree in the end, but not at the same instant.

There are two ways to run a saga. In choreography, there is no coordinator: the order service publishes "OrderCreated", the payment service reacts by charging and publishes "PaymentCompleted", inventory reacts to that and publishes "StockReserved" or "StockFailed", and payment reacts to "StockFailed" by refunding.

Each service knows only which events it listens to and which it emits.

In orchestration, one component — an orchestrator, typically living in the order service — holds the saga's state and sends commands in order: "charge this", wait for the reply, "reserve this", wait, and on failure "refund this".

Choreography is loosely coupled and simple for three steps, but by eight steps nobody can answer "where is order 123 right now?" without reading six services' logs.

Orchestration puts the whole flow in one readable place, at the cost of one more thing that can fail and that every step depends on.

The senior rule is: choreography for short flows with few steps and few participants; orchestration when the flow has more than three or four steps, branches, or needs a human-readable status.

Temporal is the widely used orchestration engine for durable workflows as of 2026; a persisted state machine in the order service's own database is the boring in-house alternative.

Order (orchestrator) Payment Inventory 1 · order PENDING 2 · charge $340 card charged PaymentCompleted 3 · reserve 2 × SKU-88 out of stock StockFailed C2 · refund $340 C1 · order CANCELLED compensations run in reverse order: undo step 2, then step 1 between 2 and C2 the customer is charged — that window is the design
Fig. E7.3 — An orchestrated saga for one checkout. The highlighted path is the failure: inventory says no, so the orchestrator issues compensations in reverse. Nothing is "rolled back" — the refund is a new, visible action.

Pattern: Saga (orchestration)

The problem: Without a saga, a checkout that fails at the third step leaves the first two committed and nobody responsible for undoing them.

table state when inventory times outruns offline
orders-db.orders        7c1e | PENDING          (committed, never finished)
payments-db.payments    p-91 | CHARGED  340.00   (committed, card already debited)
inventory-db.stock      SKU-88 | available 10    (nothing reserved)

order-service -> inventory-service   reserve 2 x SKU-88    ✗ timeout after 2000 ms
Result: the customer is charged for an order that will never ship.

How it works: One component, the orchestrator, stores the saga's state in a saga_state table and drives the steps in order.

  1. Record: before each step, the orchestrator writes the step as RUNNING in its own database.
  2. Command: it sends the command (charge, reserve) and waits for the reply, then marks the step DONE.
  3. Fail: if a step fails, the saga status becomes COMPENSATING.
  4. Compensate: it runs the undo action for each DONE step, in reverse order, until the saga is COMPENSATED.

Happy path, the saga_state row after each step:

saga_state: happy pathruns offline
# illustrative output          saga s-1, order 7c1e
moment         status     create_order  charge_payment  reserve_stock
after start    RUNNING    -             -               -
after step 1   RUNNING    DONE          -               -
after step 2   RUNNING    DONE          DONE            -
after step 3   COMPLETED  DONE          DONE            DONE

Failure at the stock step, with the compensations running in reverse (refund first, then cancel):

saga_state: failure with compensationsruns offline
# illustrative output          saga s-1, order 7c1e
moment            status        create_order  charge_payment  reserve_stock
after step 2      RUNNING       DONE          DONE            -
step 3 answers    COMPENSATING  DONE          DONE            FAILED (out of stock)
C2 refund $340    COMPENSATING  DONE          REFUNDED        FAILED
C1 cancel order   COMPENSATED   CANCELLED     REFUNDED        FAILED

side effects:  payments.p-91  CHARGED -> REFUNDED      orders.7c1e  PENDING -> CANCELLED

The setup: The state table, and an orchestrator that persists each transition before it acts.

V3__saga_state.sqlruns offline
CREATE TABLE saga_state (
    saga_id         UUID PRIMARY KEY,
    order_id        UUID NOT NULL,
    status          TEXT NOT NULL,          -- RUNNING, COMPENSATING, COMPLETED, COMPENSATED, NEEDS_HUMAN
    create_order    TEXT,                   -- DONE, CANCELLED
    charge_payment  TEXT,                   -- DONE, REFUNDED
    reserve_stock   TEXT,                   -- DONE, FAILED
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);
CheckoutSaga.java (sketch; the client types are assumed)runs offline
void run(UUID sagaId, UUID orderId, String sku, int qty, BigDecimal amount) {
    record(sagaId, "create_order", "DONE");
    try {
        payment.charge(orderId, amount);          // step 2
        record(sagaId, "charge_payment", "DONE"); // persisted BEFORE the next call
        inventory.reserve(orderId, sku, qty);     // step 3
        record(sagaId, "reserve_stock", "DONE");
        finish(sagaId, "COMPLETED");
    } catch (OutOfStockException e) {
        record(sagaId, "reserve_stock", "FAILED");
        finish(sagaId, "COMPENSATING");
        payment.refund(orderId);                  // C2: undo step 2 first (idempotent: keyed by orderId)
        record(sagaId, "charge_payment", "REFUNDED");
        orders.cancel(orderId);                   // C1: then undo step 1
        record(sagaId, "create_order", "CANCELLED");
        finish(sagaId, "COMPENSATED");
    }
}

What you see: One query answers "where is order 7c1e right now?", and the log shows the compensation order.

without the sagaruns offline
# illustrative output
$ psql orders-db -c "SELECT status FROM orders WHERE id = '7c1e'"
 PENDING            -- forever; no row anywhere says why, or what else happened
with the sagaruns offline
# illustrative output
$ psql orders-db -c "SELECT status, charge_payment, reserve_stock FROM saga_state WHERE order_id = '7c1e'"
 COMPENSATED | REFUNDED | FAILED
14:02:12.440 saga s-1 reserve_stock FAILED (out of stock)
14:02:12.455 saga s-1 refund 340.00 -> REFUNDED
14:02:12.470 saga s-1 order 7c1e -> CANCELLED

The trap: The orchestrator dies mid-saga, or a compensation itself fails; if state was not persisted, nobody knows what is half-done.

stuck sagaruns offline
# illustrative output  (orchestrator pod killed between C2 and C1)
saga s-1  COMPENSATING  create_order=DONE  charge_payment=REFUNDED  reserve_stock=FAILED
restart: recovery job finds status=COMPENSATING -> skips the refund (already REFUNDED) -> runs C1 only   ✓
refund rejected permanently by the gateway -> status NEEDS_HUMAN, alert fires                          ✓

When to use it / when not: Use orchestration when the flow is long enough that someone must be able to see it in one place.

Pattern: Saga (choreography)

The problem: With no coordinator, the flow exists only as a set of "who listens to what" decisions spread over many services, and nobody can read it in one place.

where is order 7c1e?runs offline
# illustrative output
$ for s in order payment inventory shipping; do kubectl logs deploy/$s-service | grep 7c1e; done
order-service      OrderCreated 7c1e
payment-service    charged 7c1e 340.00
inventory-service  StockFailed 7c1e
shipping-service   (nothing)
# did the refund happen? you must go and read the payment log again to find out

How it works: Each service reacts to events and emits its own; the compensation is just another reaction.

event chain for the failure pathruns offline
step  service    reacts to          publishes
1     order      (HTTP request)     OrderCreated
2     payment    OrderCreated       PaymentCompleted   ✓ charged $340
3     inventory  PaymentCompleted   StockFailed        ✗ out of stock
4     payment    StockFailed        PaymentRefunded    C2: refund
5     order      PaymentRefunded    OrderCancelled     C1: cancel

The setup: The payment service's side of step 4: it listens, refunds idempotently, and answers through its own outbox.

PaymentCompensationListener.java (sketch; OrderEvent, payments and outbox types are assumed)runs offline
@KafkaListener(topics = "Order", groupId = "payment-service")
@Transactional
public void onOrderEvent(String payload) throws Exception {
    OrderEvent evt = json.readValue(payload, OrderEvent.class);
    if (!"StockFailed".equals(evt.type())) return;     // not my concern
    payments.refundOnce(evt.orderId());                // ✅ idempotent: keyed by order id
    outbox.add("Order", evt.orderId(), "PaymentRefunded");
}

What you see: The same question, answered by the orchestrated version in one row and by the choreographed version only by joining logs.

choreography versus orchestrationruns offline
# illustrative output
choreography:  4 services x 1 log each, joined by trace id      -> "refunded, order cancelled"
orchestration: SELECT status FROM saga_state WHERE order_id=... -> COMPENSATED

The trap: Flows grow by adding listeners, and a cycle of events nobody drew can loop forever.

accidental cycleruns offline
# illustrative output
PaymentRefunded  -> order cancels          ✓
OrderCancelled   -> promo re-issues voucher -> VoucherIssued
VoucherIssued    -> order "re-evaluates"   -> OrderUpdated -> promo ... ✗ no service owns the loop

When to use it / when not: Choreography is for short flows with few participants.

The dual-write problem, and the outbox that solves it

Every saga step has the same hidden trap, called the dual-write problem: the order service must write to two systems that share no transaction.

  1. (a) insert the order row into its database.
  2. (b) publish "OrderCreated" to Kafka.

Either order of the two writes is wrong, in a different way.

Every "we lost an event" incident in an event-driven system traces back to this.

The setup: The tempting code: save the row, then send the event.

OrderService.java (the dual write)runs offline
@Transactional
public UUID place(String sku, int quantity, BigDecimal amount) throws Exception {
    Order order = newOrder(sku, quantity, amount);
    orders.save(order);                                   // write 1: database (commits when the method returns)
    kafka.send("Order", order.id.toString(), payload);    // ❌ TRAP: write 2: broker, outside the transaction
    return order.id;                                      // process killed here: ✗ between write 1 and write 2
}

Make the invisible visible: Look at both systems at the instant the process dies after the insert has committed and before the send.

table and broker state at the crashruns offline
# illustrative output
orders table (orders-db)                    topic Order (broker)
7c1e | PENDING | committed 14:02:11          offset 41  (another order's event)
                                            offset 42  (nothing for 7c1e)

The trace: Both orders of the two writes, step by step.

call traceruns offline
(a) then (b):   insert order      ✓ committed
                process killed    ✗
                publish event     ✗ never happens      -> order exists, saga never starts

(b) then (a):   publish event     ✓ payment sees it, charges $340
                insert order      ✗ constraint error   -> money taken for an order that is not there

What you see: The two systems disagree and nothing reports an error.

consoleruns offline
# illustrative output
orders-db:        SELECT status FROM orders WHERE id='7c1e';        -> PENDING
payment-service:  (no log line mentions 7c1e)
broker:           no message with key 7c1e on topic Order

Why: A database commit and a broker send are two separate operations with no coordinator between them, so a crash can fall between them.

The fix: The transactional outbox, described next, writes to one system only. What you see now: the order row and the event row exist together or not at all, as shown in the outbox pattern below.

The transactional outbox pattern fixes it by refusing to write to two systems at all. The service writes the order row and a row describing the event into an outbox table, in the same local database transaction — which is atomic, because it is one database.

A separate process then reads new outbox rows and publishes them to Kafka, marking each one as sent.

If the process dies after publishing but before marking, the row is published again on restart, so the outbox gives at-least-once delivery, and consumers must tolerate duplicates (which they must anyway with Kafka).

The reader can be a polling loop in the same service — simple, fine up to a few thousand events a second — or it can be change data capture (CDC): a tool that reads the database's own transaction log (the write-ahead log from Chapter E8) and turns every committed outbox insert into a Kafka message with no polling at all.

Debezium is the standard CDC tool as of 2026 (3.x line), it runs as a Kafka Connect connector, and it has a built-in "outbox event router" that turns an outbox row into a properly keyed event on the right topic.

Dual write: two systems, no shared commit Outbox + CDC: one commit, log does the rest order service orders db Kafka 1 insert 2 publish crash between 1 and 2: order exists, event lost crash between 2 and commit: event sent, order gone order service orders db orders row + outbox row ONE commit Debezium reads WAL Kafka crash anywhere: the row is committed or it is not; the log is replayed, so the event is delivered at least once The outbox turns "write to two systems" into "write to one system, and let something reliable copy it"
Fig. E7.4 — Dual write on the left loses or leaks events at every crash point. The outbox on the right has one commit; the highlighted arrow is the only write the service makes, and the transaction log carries the event out.

Pattern: Transactional outbox

The problem: The dual write above: the order is committed but the event never leaves, or the event leaves for an order that was never committed.

How it works: The service writes the order and the event as two rows in one local transaction; a separate relay copies the event row to Kafka.

  1. Commit: one transaction inserts the orders row and the outbox row. Either both exist or neither does.
  2. Relay: a poller (or Debezium reading the write-ahead log) finds outbox rows not yet sent and publishes each to Kafka.
  3. Mark: after the broker acknowledges, the relay stamps published_at. A crash before the stamp means the row is sent again: at-least-once.
table state: commit, relay, crash, replayruns offline
# illustrative output
moment                                orders                outbox (id, type, published_at)    broker topic Order
1 one transaction commits             7c1e PENDING          e-1 OrderCreated  NULL             (empty)
2 relay sends e-1, broker acks        7c1e PENDING          e-1 OrderCreated  NULL             offset 42: e-1
3 relay killed before the stamp       7c1e PENDING          e-1 OrderCreated  NULL             offset 42: e-1
4 relay restarts, sends e-1 again     7c1e PENDING          e-1 OrderCreated  NULL             offset 42: e-1, offset 43: e-1  (duplicate)
5 relay stamps published_at           7c1e PENDING          e-1 OrderCreated  14:02:12         unchanged

The setup: The polling version is the SQL and the Java in the next sub-section (V2__outbox.sql, OrderService, OutboxPoller). The change-data-capture version replaces the poller with a Debezium connector:

outbox-connector.json (Kafka Connect; database connection settings omitted)runs offline
{
  "name": "orders-outbox",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "table.include.list": "public.outbox",
    "transforms": "outbox",
    "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter",
    "transforms.outbox.table.field.event.key": "aggregate_id",
    "transforms.outbox.route.by.field": "aggregate_type"
  }
}

What you see: The same kill -9 between the two writes, without and with the outbox.

without the patternruns offline
# illustrative output
orders:  7c1e PENDING
broker:  nothing for 7c1e          -> ✗ order exists, event lost, saga never starts
with the patternruns offline
# illustrative output
orders:  7c1e PENDING          outbox: e-1 OrderCreated published_at=NULL     (process killed here)
restart: relay selects e-1 -> sends -> broker offset 42 -> published_at = 14:02:12   ✓ event delivered

The trap: The outbox table is only ever appended to, so it grows without limit unless something deletes published rows; and a relay that sends twice means consumers must cope with duplicates.

consoleruns offline
# illustrative output
SELECT count(*) FROM outbox;                    -> 48213907    ✗ nobody deletes published rows
SELECT count(*) FROM outbox WHERE published_at IS NULL;   -> 12       (the partial index keeps this query cheap)
-- ✅ FIX: DELETE FROM outbox WHERE published_at < now() - interval '7 days';   (or delete right after insert with CDC)

When to use it / when not: Use it whenever a database change must be announced to other services.

The outbox as SQL, and the consumer that tolerates duplicates

Here is the outbox schema the order service uses, in PostgreSQL, followed by the inventory service's Kafka listener showing the receiving side: an idempotent consumer that records which event ids it has already processed, in the same transaction as its business change, so a redelivered event is a no-op.

Step-by-step: what V2__outbox.sql does, in plain English
  1. Creates the outbox table. Each row is one event to publish: a unique event id (which becomes the idempotency key on the consumer side), the aggregate_type and aggregate_id (which become the Kafka topic and message key, so all events for one order land on one partition in order), the event type, and the JSON payload.
  2. created_at records when the event was written; published_at is null until a poller marks it sent. With Debezium the poller does not exist and rows can be deleted immediately after insert — Debezium sees the insert in the log regardless.
  3. The partial index on unpublished rows makes the poller's "give me the next batch" query cheap even when the table has millions of published rows.
  4. Creates the processed_events table used by every consumer: one row per event id it has handled. Inserting into it inside the consumer's business transaction is what makes the consumer idempotent.
order-service/src/main/resources/db/migration/V2__outbox.sqlruns offline
-- Transactional outbox: written in the SAME transaction as the business row.
CREATE TABLE outbox (
    id              UUID        PRIMARY KEY,           -- event id = consumer idempotency key
    aggregate_type  TEXT        NOT NULL,              -- 'Order'  -> topic name via router
    aggregate_id    TEXT        NOT NULL,              -- order id -> Kafka message key
    type            TEXT        NOT NULL,              -- 'OrderCreated', 'OrderCancelled'
    payload         JSONB       NOT NULL,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    published_at    TIMESTAMPTZ NULL                   -- used by a poller; unused with CDC
);

-- The poller only ever asks for unpublished rows, oldest first.
CREATE INDEX outbox_unpublished_idx
    ON outbox (created_at)
    WHERE published_at IS NULL;

-- Every consuming service keeps this table in ITS OWN database.
-- Inserting the event id here, inside the business transaction,
-- turns at-least-once delivery into exactly-once effect.
CREATE TABLE processed_events (
    event_id      UUID        PRIMARY KEY,
    consumer      TEXT        NOT NULL,
    processed_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);
Step-by-step: what OrderService.java and StockReservationListener.java do, in plain English
  1. OrderService.place(...) runs under @Transactional. It saves the order and, in the same transaction, saves an OutboxEvent row whose payload is the serialised event. Either both rows commit or neither does; Kafka is never touched here.
  2. OutboxPoller.publishBatch() runs every 200 ms. It selects up to 100 unpublished rows, sends each to Kafka with the aggregate id as the message key, waits for the broker's acknowledgement with .get(), and only then stamps published_at. If the process dies after sending but before stamping, the row is sent again — at-least-once by design.
  3. The SELECT ... FOR UPDATE SKIP LOCKED query lets several instances of the service poll at once without publishing the same row twice concurrently: each instance locks the rows it took and skips rows another instance holds.
  4. On the inventory side, StockReservationListener.onOrderCreated(...) is a Kafka listener. It reads the event id from the message and first tries to insert it into processed_events; a primary-key violation means "seen before", so it returns without doing anything.
  5. If the insert succeeds, the reservation is made in the same transaction. Kafka's offset is committed only after the listener returns, so if the transaction rolls back, the message will be redelivered and the whole method runs again from the top.
  6. The @KafkaListener is grouped under inventory-service; all instances of the inventory service share the partitions of the Order topic, and because the message key is the order id, every event for one order goes to one instance in order.
order-service/src/main/java/shop/orders/OrderService.javaruns offline
package shop.orders;

// Extra dependencies for this file:
//   implementation("org.springframework.boot:spring-boot-starter-data-jpa")
//   implementation("org.springframework.kafka:spring-kafka")
//   implementation("org.flywaydb:flyway-database-postgresql")
//   runtimeOnly("org.postgresql:postgresql")

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;

@Entity
@Table(name = "orders")
class Order {
    @Id UUID id;
    String sku;
    int quantity;
    BigDecimal amount;
    String status;
}

@Entity
@Table(name = "outbox")
class OutboxEvent {
    @Id UUID id;
    String aggregateType;
    String aggregateId;
    String type;
    @org.hibernate.annotations.JdbcTypeCode(org.hibernate.type.SqlTypes.JSON)
    String payload;
    OffsetDateTime createdAt;
    OffsetDateTime publishedAt;
}

interface OrderRepository extends JpaRepository<Order, UUID> {}

interface OutboxRepository extends JpaRepository<OutboxEvent, UUID> {
    // SKIP LOCKED: several poller instances can run without double-publishing.
    @Query(value = """
            SELECT * FROM outbox
             WHERE published_at IS NULL
             ORDER BY created_at
             LIMIT 100
             FOR UPDATE SKIP LOCKED
            """, nativeQuery = true)
    List<OutboxEvent> nextUnpublished();
}

record OrderCreated(UUID eventId, UUID orderId, String sku, int quantity, BigDecimal amount) {}

@Service
public class OrderService {

    private final OrderRepository orders;
    private final OutboxRepository outbox;
    private final ObjectMapper json;

    OrderService(OrderRepository orders, OutboxRepository outbox, ObjectMapper json) {
        this.orders = orders;
        this.outbox = outbox;
        this.json = json;
    }

    // ONE local transaction writes the order AND the event. Kafka is not involved.
    @Transactional
    public UUID place(String sku, int quantity, BigDecimal amount) throws Exception {
        Order order = new Order();
        order.id = UUID.randomUUID();
        order.sku = sku;
        order.quantity = quantity;
        order.amount = amount;
        order.status = "PENDING";
        orders.save(order);

        OutboxEvent evt = new OutboxEvent();
        evt.id = UUID.randomUUID();
        evt.aggregateType = "Order";
        evt.aggregateId = order.id.toString();
        evt.type = "OrderCreated";
        evt.payload = json.writeValueAsString(
                new OrderCreated(evt.id, order.id, sku, quantity, amount));
        evt.createdAt = OffsetDateTime.now();
        outbox.save(evt);

        return order.id;
    }
}

@Component
class OutboxPoller {

    private final OutboxRepository outbox;
    private final KafkaTemplate<String, String> kafka;

    OutboxPoller(OutboxRepository outbox, KafkaTemplate<String, String> kafka) {
        this.outbox = outbox;
        this.kafka = kafka;
    }

    // Poll-based relay. Swap for Debezium's outbox router at higher volume.
    @Scheduled(fixedDelay = 200)
    @Transactional
    public void publishBatch() throws Exception {
        for (OutboxEvent evt : outbox.nextUnpublished()) {
            // Topic = aggregate type; key = aggregate id, so one order's events stay ordered.
            kafka.send(evt.aggregateType, evt.aggregateId, evt.payload).get();
            evt.publishedAt = OffsetDateTime.now();   // stamped only after the broker acked
        }
    }
}
inventory-service/src/main/java/shop/inventory/StockReservationListener.javaruns offline
package shop.inventory;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.UUID;

record OrderCreated(UUID eventId, UUID orderId, String sku, int quantity, BigDecimal amount) {}

@Component
public class StockReservationListener {

    private final JdbcTemplate db;
    private final ObjectMapper json;

    StockReservationListener(JdbcTemplate db, ObjectMapper json) {
        this.db = db;
        this.json = json;
    }

    // Offset is committed after this method returns normally. If the transaction
    // rolls back, Kafka redelivers and we run again from the top.
    @KafkaListener(topics = "Order", groupId = "inventory-service")
    @Transactional
    public void onOrderCreated(String payload) throws Exception {
        OrderCreated evt = json.readValue(payload, OrderCreated.class);

        // Idempotency guard: the event id is the primary key. A duplicate delivery
        // (rebalance, poller re-send, our own crash after commit) hits the PK and stops here.
        try {
            db.update("INSERT INTO processed_events (event_id, consumer) VALUES (?, ?)",
                      evt.eventId(), "inventory-service");
        } catch (DataIntegrityViolationException alreadyProcessed) {
            return;
        }

        // Business change in the SAME transaction as the guard row.
        int reserved = db.update("""
                UPDATE stock
                   SET available = available - ?
                 WHERE sku = ? AND available >= ?
                """, evt.quantity(), evt.sku(), evt.quantity());

        String outcome = reserved == 1 ? "StockReserved" : "StockFailed";
        db.update("""
                INSERT INTO outbox (id, aggregate_type, aggregate_id, type, payload)
                VALUES (?, 'Order', ?, ?, ?::jsonb)
                """, UUID.randomUUID(), evt.orderId().toString(), outcome,
                json.writeValueAsString(evt));
    }
}

Read the two halves together and the guarantee falls out. The producer never loses an event, because the event is a row in the same commit as the order. The relay may send the same row twice, so delivery is at least once. The consumer turns at-least-once delivery into exactly-once effect, because the guard row and the stock update commit together: if the event is redelivered after a successful commit, the guard's primary key rejects it; if the process crashed before commit, neither the guard nor the stock change exists and the redelivery does the work cleanly. Notice too that the inventory service answers through its own outbox — the saga's next step is triggered the same reliable way. That symmetry is what "event-driven" should mean in practice: every service reads from a log, writes to its database and its outbox in one transaction, and lets a relay carry the result onward.

Pattern: Idempotent consumer

The problem: At-least-once delivery means the same message arrives twice, and a consumer that is not idempotent applies it twice.

stock after a duplicate, without the guardruns offline
# illustrative output
delivery #1  offset 42  event e-1  reserve 2 x SKU-88   stock.available 10 -> 8
delivery #2  offset 42  event e-1  reserve 2 x SKU-88   stock.available  8 -> 6   ✗ reserved twice

How it works: The consumer records every event id it has handled, in the same transaction as the business change.

  1. Insert first: inside the transaction, insert the event id into processed_events (this is the processed-messages ledger; its primary key is the event id).
  2. Stop on duplicate: a primary-key violation means "seen before", so return without doing anything.
  3. Change and commit together: if the insert succeeded, apply the business change in the same transaction. Both commit or neither does.
message timeline: the same id delivered twiceruns offline
# illustrative output
delivery  offset  event_id  processed_events          stock SKU-88  result
#1        42      e-1       empty -> insert e-1       10 -> 8       ✓ applied
#2        42      e-1       e-1 exists, PK rejects    8 -> 8        ✓ skipped, no effect
crash case: transaction rolled back -> neither row exists -> redelivery does the work once   ✓

The setup: The listener above uses a try/catch on the primary-key violation. A variant that avoids the exception uses ON CONFLICT DO NOTHING and checks the update count:

idempotency guard (variant)runs offline
int inserted = db.update(
    "INSERT INTO processed_events (event_id, consumer) VALUES (?, ?) ON CONFLICT DO NOTHING",
    evt.eventId(), "inventory-service");
if (inserted == 0) {
    return;                       // ✅ duplicate: already processed, do nothing
}
// ...business change follows in the SAME transaction

What you see: The stock number after the same duplicate, with the guard.

with the patternruns offline
# illustrative output
delivery #1  offset 42  event e-1  stock.available 10 -> 8
delivery #2  offset 42  event e-1  ignored (processed_events has e-1)   stock.available 8 -> 8   ✓

The trap: Recording the id in a different transaction from the business change.

guard committed, change lostruns offline
# illustrative output
tx A: INSERT processed_events e-1       ✓ committed
      process killed before tx B         ✗
tx B: UPDATE stock ...                   never runs
redelivery of e-1: guard says "seen"   -> skipped   ✗ the reservation never happened, and never will
# ✅ FIX: guard row and business change in ONE transaction (as in the listener above)

When to use it / when not: Use it on every consumer of an at-least-once channel that changes state.

Pattern: Dead-letter queue

The problem: One message that can never be processed (a poison message) is retried forever, and every message behind it on that partition waits.

consumer lag with a poison messageruns offline
# illustrative output
ERROR inventory-service cannot parse payload at topic Order, partition 0, offset 42 (attempt 1)
ERROR inventory-service cannot parse payload at topic Order, partition 0, offset 42 (attempt 2) ...
PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG
0          42              1042            1000       ✗ stuck behind one bad record

How it works: Retry a few times, then park the message somewhere else and keep going.

  1. Retry: the consumer retries the record a small, fixed number of times with a delay.
  2. Park: after the last retry, the record is published to a dead-letter topic (by default the original topic name plus .DLT in Spring Kafka) together with the error details.
  3. Move on: the offset is committed and the partition continues; an alert fires on the dead-letter topic.
  4. Repair: a person or a job inspects the parked record, fixes the cause, and replays it.

The setup: Spring Kafka needs one error-handler bean; Spring Boot applies it to the listeners.

KafkaErrorConfig.javaruns offline
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
    var recoverer = new DeadLetterPublishingRecoverer(template);   // publishes to Order.DLT
    return new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3L)); // 3 retries, 1 s apart
}

What you see: The same partition after the handler is in place.

with the patternruns offline
# illustrative output
PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG
0          1042            1042            0          ✓ moved past offset 42
topic Order.DLT   1 record   (key 7c1e, error header: cannot parse payload)

The trap: A dead-letter topic that nobody watches is just a slower way to lose messages, and a message that failed only because a dependency was briefly down should be retried, not parked.

unwatched dead-letter topicruns offline
# illustrative output
Order.DLT  LAG 0 consumers   3,902 records   oldest: 41 days ago     ✗ no alert, no owner, no replay job

When to use it / when not: Use it on any consumer whose input you do not fully control.

CQRS, and why nobody uses two-phase commit

Pattern: CQRS

CQRS — command query responsibility segregation — is the idea of using different models for writing and for reading.

The order service's write model is normalised and guarded by rules; a separate read model, built by consuming events, is shaped for a particular screen ("orders with customer name and shipping status", which in a monolith was a three-table JOIN).

The read model may be a denormalised table in another service, an Elasticsearch index, or a Redis hash.

The cost is that the read model lags the write model by however long the events take to arrive — usually milliseconds, occasionally minutes during an incident — so the UI must be designed to tolerate "your order will appear shortly".

Use CQRS where reads need a shape the write model cannot give cheaply; do not use it because it sounds architectural.

The problem: The orders screen needs order, customer name and shipping status, which live in three services, so the monolith's JOIN is gone.

How it works: A listener keeps a table shaped exactly like the screen, updated from events. The screen reads that table only.

table state: the read model after each eventruns offline
# illustrative output          order_view(order_id, customer_name, status, shipping_status)
event                        row
OrderCreated 7c1e            7c1e | Priya S. | PENDING   | NONE
PaymentCompleted 7c1e        7c1e | Priya S. | CONFIRMED | NONE
ShipmentDispatched 7c1e      7c1e | Priya S. | CONFIRMED | DISPATCHED

The setup: The read table and the idempotent statements the listener runs (a replayed event changes nothing).

V4__order_view.sqlruns offline
CREATE TABLE order_view (
    order_id         UUID PRIMARY KEY,
    customer_name    TEXT,
    status           TEXT NOT NULL,
    shipping_status  TEXT NOT NULL DEFAULT 'NONE',
    updated_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- on OrderCreated:       INSERT INTO order_view (order_id, status) VALUES (?, 'PENDING') ON CONFLICT (order_id) DO NOTHING;
-- on ShipmentDispatched: UPDATE order_view SET shipping_status = 'DISPATCHED', updated_at = now() WHERE order_id = ?;

What you see: One query for the screen, and the lag between a command and its visible effect.

read-after-write lagruns offline
# illustrative output
14:02:11.318  POST /orders                     -> 201   (write model committed)
14:02:11.330  GET  /order-view?id=7c1e         -> 404   ✗ event not applied yet
14:02:11.560  GET  /order-view?id=7c1e         -> 200   PENDING   ✓ lag was about 240 ms

The trap: Users read their own write straight after making it and see nothing.

what to do about itruns offline
# ✅ FIX options
return the new order in the POST response body      (screen shows it without reading the view)
or show "your order will appear shortly" and poll   (the UI is designed for the lag)

When to use it / when not: Use it where reads need a shape the write model cannot give cheaply.

Pattern: Event sourcing

The problem: A table that stores only the current state cannot tell you how it got there.

state onlyruns offline
# illustrative output
orders:  7c1e | CANCELLED        -- cancelled by whom, after what, was the payment refunded? unknown

How it works: Store every change as an immutable event, and compute the current state by replaying them.

  1. Append: each command that is accepted adds one event row; rows are never updated or deleted.
  2. Fold: the current state is the result of applying the events in order.
  3. Snapshot: for long histories, store a periodic snapshot and replay only the events after it.
table state: order_eventsruns offline
# illustrative output
order_id  seq  type              data
7c1e      1    OrderCreated      sku=SKU-88 qty=2
7c1e      2    PaymentCompleted  amount=340.00
7c1e      3    StockFailed       reason=out of stock
7c1e      4    OrderCancelled    cause=saga compensation
fold(1..4) = CANCELLED      fold(1..2) = PAID   (state "as of" any moment)

The setup: The unique key on (order_id, seq) is the concurrency control: two writers cannot both append sequence number 5.

V5__order_events.sqlruns offline
CREATE TABLE order_events (
    order_id  UUID    NOT NULL,
    seq       INTEGER NOT NULL,
    type      TEXT    NOT NULL,
    data      JSONB   NOT NULL,
    PRIMARY KEY (order_id, seq)     -- ✅ a concurrent writer gets a duplicate-key error and must retry
);

What you see: Two writers appending to the same order at once.

consoleruns offline
# illustrative output
writer A: INSERT order_events (7c1e, 5, 'OrderShipped', ...)      ✓
writer B: INSERT order_events (7c1e, 5, 'OrderCancelled', ...)    ✗ duplicate key value violates unique constraint
writer B reloads events 1..5, re-decides, appends seq 6 or gives up

The trap: Events live forever, so their shape must stay readable by new code, and replays get slow without snapshots.

schema driftruns offline
# illustrative output
seq 1 (2024)  OrderCreated {sku, qty}                 seq 1 (2026)  OrderCreated {sku, qty, currency}
replaying the 2024 events with the 2026 class: currency missing -> must be handled by upcasting or a default   ✗

When to use it / when not: Event sourcing is different from the outbox: the outbox announces a change, event sourcing is the storage.

Finally, the question every interviewer asks at least once: why not a real distributed transaction? Two-phase commit (2PC) does exist: a coordinator asks every participant "can you commit?", each one prepares and votes, and the coordinator then tells them all to commit or all to abort.

It gives real atomicity across databases. It is avoided in service architectures for three reasons. First, every participant holds locks from "prepare" until the coordinator's final decision arrives, so a slow or dead coordinator freezes rows in every database — availability collapses to the weakest participant.

Second, it is synchronous and blocking, which is exactly the coupling in time that services were split to escape. Third, most modern infrastructure (Kafka, HTTP services, cloud databases) does not participate in an XA transaction at all, so it cannot cover the calls you actually make.

the Distributed Systems primer has the consensus-level detail; the sentence to carry into the interview is "2PC buys atomicity by holding everyone's locks hostage to the coordinator, and sagas buy availability by making compensation explicit."

The trace: Why a coordinator crash is so costly in two-phase commit: everyone has voted yes and is holding locks, waiting for an answer that does not come.

two-phase commit traceruns offline
# illustrative output
coordinator -> order-db      PREPARE   ✓ vote yes (row locks held)
coordinator -> payment-db    PREPARE   ✓ vote yes (row locks held)
coordinator -> inventory-db  PREPARE   ✓ vote yes (row locks held)
coordinator crashes before sending COMMIT        ✗
all three databases: prepared, undecided, locks still held, other transactions queue behind them

What you see: In PostgreSQL a prepared transaction is visible in pg_prepared_xacts, and it keeps its locks until someone commits or rolls it back.

consoleruns offline
# illustrative output
SELECT gid, prepared FROM pg_prepared_xacts;
 gid          | prepared
 checkout-7c1e| 2026-08-28 14:02:11+00      -- still here an hour later; the rows it touched stay locked

There are no dumb questions

If Kafka has "exactly-once semantics", why do I still need the idempotent consumer?
Kafka's exactly-once guarantee (transactional producers plus isolation.level=read_committed) covers a pipeline that reads from Kafka and writes back to Kafka — a stream processor. It does not cover the moment your consumer writes to PostgreSQL, because PostgreSQL is not part of the Kafka transaction. The instant a consumer touches a system outside Kafka, you are back to at-least-once, and the guard table is what closes the gap.
Can two services share one database if they never touch each other's tables?
Physically sharing a server with separate schemas and separate credentials is a reasonable cost-saving stage, and it keeps the important rule: no service reads another's tables. What you lose is failure isolation — one service's runaway query can slow the other — and the ability to move one service's data elsewhere later without a migration. Treat it as "one database instance, many logical databases", and enforce the wall with database users that cannot see the other schema.
How long is "eventually" in eventual consistency?
Under normal conditions, the time for an outbox row to be relayed and consumed: tens of milliseconds with CDC, a few hundred with a poller. During an incident — a consumer crash-looping, a partition rebalance storm — it can be minutes or hours, and the design has to be honest about that: the read model shows the last known state, and business rules that cannot tolerate staleness (does this account have enough balance?) must be decided by the service that owns the truth, synchronously.
What if a compensating action itself fails?
Compensations must be retried until they succeed, which means they must be idempotent (refunding twice must not refund twice) and the saga's state must be persisted so a restart resumes the compensation. If a compensation cannot possibly succeed — the refund gateway rejects it permanently — the saga moves to a "needs human" state, alerts, and a person resolves it. Design the manual queue on day one; it is the part everyone forgets.

Quick reference — Data across services

database-per-service
No shared tables, no cross-service joins, no distributed transaction. This is the constraint everything else works around.
saga
A sequence of local transactions, each with a compensating action for undo. Not a rollback — an apology.
choreography vs orchestration
Choreography: services react to events, no coordinator, hard to see the whole flow. Orchestration: one coordinator drives, easier to reason about and to debug.
dual-write problem
Writing to your database and publishing a message are two operations. Either can fail alone, and then they disagree.
transactional outbox
Write the message into your own database, in the same transaction as the data. A separate process publishes it. This is the fix for dual-write.
at-least-once
What every real message system gives you. Which means the consumer must be idempotent — that is not optional.

05 · The primerOperability — Seeing, Measuring, Testing, and Shipping Many Services

In a monolith a stack trace tells you what happened. Across services you need a trace id threaded through every hop, and objectives that say what “healthy” means before you are asked at 3 a.m.

A number to hold onto: a single checkout on a mature service platform typically touches 15 to 40 processes — gateway, auth, order, pricing, promotions, payment, fraud, inventory, tax, shipping quote, notification, and several caches and databases.

When that checkout takes 4 seconds instead of 400 milliseconds, "look at the logs" means looking at 40 logs on 40 machines, and the slow hop could be any of them.

Without a way to follow one request across all of them, the platform is not debuggable, and a system that cannot be debugged cannot be operated.

This chapter is about the four disciplines that keep a many-service system operable: observability, service-level objectives, safe deployment, and contract testing.

Interviews at the senior level spend as much time here as on the architecture itself, because the architecture is what you draw and operability is what you live with.

Bridge: from the stack trace to the distributed trace

In the monolith, when a request was slow you had a profiler and a stack trace: one process, one timeline, every method's time nested inside its caller's. A distributed trace rebuilds that picture across processes.

Each unit of work — an HTTP request handled, a database query, a Kafka message consumed — is recorded as a span: a name, a start time, a duration, and some attributes.

Every span carries the id of the span that caused it, and all spans of one user request share a trace id.

The trace id travels between services in a header — the W3C standard header is called traceparent — and into Kafka messages as a message header, so a consumer's span can point back at the producer's.

Assemble all spans with the same trace id, sort by time, and you have a waterfall diagram that is exactly the stack trace you lost, with the network hops made visible.

The tool everyone converged on is OpenTelemetry (OTel), the vendor-neutral standard for producing traces, metrics, and logs; in Spring Boot 3.5+ and 4.x, Micrometer Tracing wired to an OTel exporter emits spans automatically for every controller, RestClient call, JDBC query, and Kafka listener, with zero code, as long as the starter is on the classpath and an endpoint is configured.

There are three signals, and each answers a different question.

The connecting thread is the correlation id: put the trace id into every log line.

One trace id · spans nested by cause · time runs left to right 0 ms 1 s 2 s 3 s gateway POST /checkout order POST /orders order INSERT orders, outbox payment POST /payments fraud POST /score 2,440 ms — model cold start payment card processor inventory Kafka consume Order async span linked via message header Total 2.9 s. The waterfall makes the answer obvious: 84% of the time is one span, three hops deep, in a service nobody suspected.
Fig. E7.5 — A trace waterfall for one slow checkout. Each bar is a span; indentation shows which span caused which. The highlighted span is the culprit, and no single service's dashboard would have shown it.

The configuration: tracing, metrics, and correlated logs in one file

Here is the complete Spring Boot configuration that turns on all three signals and ships traces to an OpenTelemetry Collector — the standard relay process that receives telemetry, batches it, and forwards it to whatever backend you use (Jaeger or Tempo for traces, Prometheus for metrics, Loki or Elasticsearch for logs). Nothing in the Java code changes.

Step-by-step: what application-observability.yml does, in plain English
  1. management.tracing.sampling.probability: 1.0 records every request. In production you would set 0.1 (one in ten) or use tail-based sampling at the collector, which keeps every slow or failed trace and drops most fast successful ones.
  2. management.otlp.tracing.endpoint is the collector's address for the OTLP protocol (the OpenTelemetry wire format) over HTTP. The dependency io.micrometer:micrometer-tracing-bridge-otel plus io.opentelemetry:opentelemetry-exporter-otlp makes Boot auto-configure the exporter.
  3. management.tracing.propagation.type: w3c tells Boot to read and write the traceparent header, so traces continue across services written in any language.
  4. management.otlp.metrics.export pushes metrics to the collector too; the Prometheus endpoint under /actuator/prometheus stays available for pull-based scraping.
  5. logging.structured.format.console: ecs switches the console log to JSON in Elastic Common Schema shape — every line becomes a record with timestamp, level, logger, message, and, because Boot's tracing adds them to the MDC, trace_id and span_id.
  6. The observations.key-values block adds the service's environment to every span and metric, so a dashboard can split staging from production.
  7. The spring.kafka lines turn on observation for producers and listeners, which is what carries the trace id inside message headers and links the inventory consumer's span to the order's trace.
order-service/src/main/resources/application-observability.ymlruns offline
# Dependencies (Spring Boot 3.5+/4.x):
#   implementation("org.springframework.boot:spring-boot-starter-actuator")
#   implementation("io.micrometer:micrometer-tracing-bridge-otel")
#   implementation("io.opentelemetry:opentelemetry-exporter-otlp")
#   implementation("io.micrometer:micrometer-registry-otlp")
#   implementation("io.micrometer:micrometer-registry-prometheus")

management:
  tracing:
    enabled: true
    sampling:
      probability: 1.0            # 0.1 in production, or tail-sample at the collector
    propagation:
      type: w3c                   # traceparent / tracestate headers
  otlp:
    tracing:
      endpoint: ${OTEL_COLLECTOR_URL:http://otel-collector:4318}/v1/traces
    metrics:
      export:
        enabled: true
        url: ${OTEL_COLLECTOR_URL:http://otel-collector:4318}/v1/metrics
        step: 30s
  observations:
    key-values:
      service.name: ${spring.application.name}
      deployment.environment: ${ENVIRONMENT:local}
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus,circuitbreakers
  endpoint:
    health:
      probes:
        enabled: true             # /actuator/health/liveness and /readiness for Kubernetes

logging:
  structured:
    format:
      console: ecs                # JSON lines with trace_id and span_id on every record
  level:
    shop: INFO

spring:
  kafka:
    template:
      observation-enabled: true   # producer span + trace headers on each message
    listener:
      observation-enabled: true   # consumer span linked to the producer's trace

Read the effect on a log line. Before this file, the order service printed Placed order 7c1e… for sku SKU-88. After it, the same event is a JSON record: {"@timestamp":"2026-08-28T14:02:11.318Z","log.level":"INFO","service.name":"order-service","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7","message":"Placed order 7c1e… for sku SKU-88"}. The trace_id is the same 32-character value the gateway, payment, and inventory services print for their parts of this checkout, and it is the same value in the trace backend. That one field is the difference between "grep four services and guess" and "click the slow span, see its logs."

Pattern: Distributed tracing

The problem: The checkout took 4 seconds and every service's own log looks fine.

logs without a trace idruns offline
# illustrative output
14:02:09.101 gateway    INFO  POST /checkout 200 in 4010 ms
14:02:09.098 order      INFO  Placed order 7c1e for sku SKU-88
14:02:09.087 payment    INFO  charge ok p-91
14:02:07.640 fraud      INFO  score 0.02
# four lines, four hosts: which one belongs to which request, and which hop was slow? ✗

How it works: One id is created at the edge and travels with the request, so every hop can be joined.

  1. Start: the gateway creates a trace id and a span id and sends them in the traceparent header.
  2. Continue: each service reads the header, creates a child span with its own span id and the caller's as parent, and passes the header on.
  3. Cross async: the producer puts the same header on the Kafka message, so the consumer's span links back to it.
  4. Join: the backend gathers all spans with that trace id and draws the waterfall.
header propagationruns offline
gateway   POST /checkout
  | traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01      (version-traceid-spanid-flags)
  v
order     POST /orders        child span, same trace id
  | traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-<order span id>-01
  v
payment   POST /payments      child span, same trace id
  v
fraud     POST /score         child span, same trace id    <- 2,440 ms, the slow span

The setup: The configuration file above is the whole setup; this call checks that a given trace id is honoured end to end.

consoleruns offline
curl -s -o /dev/null -H 'traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' \
     http://localhost:8080/checkout
# then search the trace backend for trace id 4bf92f3577b34da6a3ce929d0e0e4736

What you see: The same four log lines, with and without the trace id.

with the patternruns offline
# illustrative output
14:02:09.101 gateway    trace_id=4bf92f3577b34da6a3ce929d0e0e4736 POST /checkout 200 in 4010 ms
14:02:09.098 order      trace_id=4bf92f3577b34da6a3ce929d0e0e4736 Placed order 7c1e
14:02:09.087 payment    trace_id=4bf92f3577b34da6a3ce929d0e0e4736 charge ok p-91
14:02:07.640 fraud      trace_id=4bf92f3577b34da6a3ce929d0e0e4736 score 0.02   (span 2,440 ms)  ✓ one id, one story

The trap: The trace id is lost where the request hops to another thread or to a client that does not propagate it, so the trace breaks into two unrelated pieces.

broken contextruns offline
# illustrative output
order    trace_id=4bf92f35...  Placed order 7c1e
order    trace_id=            Sending confirmation email      ✗ ran on a plain executor thread: no context
# ✅ FIX: use executors and HTTP clients that Spring builds for you (they propagate context), or wrap custom executors with context propagation

When to use it / when not: Use it from the first service; retrofitting it later is painful.

Objectives and budgets: what "healthy" means in numbers

Three terms, in order of dependence.

The budget is the operational tool.

While plenty of budget remains, the team ships fast and takes risks; when the budget is nearly spent, feature deploys pause and reliability work takes over.

Alerts should fire on burn rate — how fast the budget is being consumed — not on raw error counts: a burn rate of 14× over the last hour means the month's budget would be gone in two days, which is worth waking someone; a burn rate of 1× is normal and should never page.

In a service architecture, set SLOs at the edges users see (the checkout API), and derive internal budgets for dependencies from them: if checkout allows 0.1% failures and payment is on the critical path, payment must do better than 0.1% or checkout has no budget for anything else.

error budget arithmeticruns offline
SLO 99.9% over 30 days, 10,000,000 checkouts  ->  budget = 0.1% x 10,000,000 = 10,000 failures
burn rate 1x   ->  budget lasts 30 days          (normal, never pages)
burn rate 14x  ->  30 days / 14 = about 2.1 days (worth waking someone)

Shipping safely: blue/green, canary, and the contract test

Forty deploys a day are only safe if each one can be undone in seconds and can be watched before it takes full traffic.

Blue/green deployment keeps two complete copies of a service: blue is live, green gets the new version, traffic switches over all at once at the load balancer, and switching back is a one-line rollback. It is simple and its cost is double capacity during the switch.

Canary deployment sends a small slice of real traffic — 1%, then 10%, then 50% — to the new version while watching its error rate and latency against the old version, and promotes or rolls back automatically.

In Kubernetes this is what Argo Rollouts or Flagger do, using the service mesh or an ingress controller to split traffic and Prometheus metrics to judge.

The canary is the tool that turns "we think this is safe" into "we measured this on 1% of users for ten minutes and the p99 did not move".

The prerequisite for either is that the new version and the old version can run at the same time against the same database and the same consumers — which means every schema change and every API change must be backward compatible for at least one release.

That rule, more than any tool, is what makes continuous deployment possible.

Backward compatibility is where contract testing comes in. An end-to-end test that starts all forty services is slow, flaky, and tells you only that something broke.

A consumer-driven contract test flips the arrangement: each consumer of an API writes down, as an executable contract, exactly which fields and status codes it relies on.

The tool Pact records those expectations from the consumer's tests into a contract file, publishes it to a broker, and then runs the contract against the provider in the provider's own build.

If the payment team renames paymentId to id, the order service's contract fails in the payment service's pipeline before deploy — with the name of the consumer that would break.

Pact's can-i-deploy command asks the broker whether a given provider version is compatible with every consumer version currently in production, which is the question a deploy gate actually needs answered.

The senior habit is to pair contract tests with tolerant readers: consumers ignore fields they do not know and never fail on an added enum value, so providers can add freely and only removals and renames need coordination.

Pattern: Blue/green deployment

The problem: Replacing instances in place means a window where the new version is half-rolled and a slow, risky rollback.

How it works: Two complete copies run side by side and only the traffic switch moves.

  1. Deploy green: the new version starts next to blue, which still serves everyone; smoke tests run against green.
  2. Switch: the load balancer (or the Kubernetes Service selector) sends all traffic to green.
  3. Keep blue: blue stays up and idle; if the error rate rises, switch back.
traffic state over timeruns offline
# illustrative output
moment            blue (v1)             green (v2)            traffic
t0 before         running, serving      starting, smoke test  100% blue
t1 switch         running, idle         running, serving      100% green
t2 error spike    running, serving      running, idle         switch back: 100% blue   ✓ one command

The setup: In Kubernetes the switch is one selector change on the Service.

order-service Serviceruns offline
apiVersion: v1
kind: Service
metadata:
  name: order-service
spec:
  selector:
    app: order-service
    color: green        # ✅ switch: was "blue"; set back to "blue" to roll back
  ports:
    - port: 80
      targetPort: 8080

What you see: A deploy and a rollback, in numbers.

consoleruns offline
# illustrative output
$ kubectl patch service order-service -p '{"spec":{"selector":{"app":"order-service","color":"green"}}}'
service/order-service patched        # 100% on v2 within seconds
$ kubectl patch service order-service -p '{"spec":{"selector":{"app":"order-service","color":"blue"}}}'
service/order-service patched        # rollback: seconds, no rebuild

The trap: Green ran a database migration that blue cannot read, so the "instant rollback" lands on a broken version.

rollback onto an incompatible schemaruns offline
# illustrative output
green deploy:  ALTER TABLE orders RENAME COLUMN status TO state;       ✓
rollback to blue (v1) ...
blue:  ERROR: column "status" does not exist                           ✗ rollback is not safe
# ✅ FIX: expand first (add "state", keep "status"), switch, and only remove "status" a release later

When to use it / when not: Use it when you can afford double capacity for a short time.

Pattern: Canary release

The problem: Switching everyone at once means a bug reaches 100% of users before anyone has measured anything.

How it works: A small slice of real traffic goes to the new version, and the rollout widens only while the numbers stay good.

  1. Start small: 1% of traffic to the new version.
  2. Compare: error rate and latency of new versus old, for a fixed time.
  3. Widen or abort: good numbers move it to 10%, 50%, 100%; bad numbers send everything back to the old version automatically.
canary stagesruns offline
# illustrative output
stage  weight  window  error rate new vs old   p99 new vs old    decision
1      1%      10 min  0.1% vs 0.1%             180 ms vs 175 ms  ✓ continue
2      10%     10 min  0.1% vs 0.1%             182 ms vs 176 ms  ✓ continue
3      50%     10 min  2.3% vs 0.1%             640 ms vs 178 ms  ✗ abort: back to 0%

The setup: Argo Rollouts expresses the stages as steps; the traffic split is done by the mesh or the ingress controller.

order-service Rollout (strategy only)runs offline
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: order-service
spec:
  strategy:
    canary:
      steps:
        - setWeight: 1
        - pause: { duration: 10m }
        - setWeight: 10
        - pause: { duration: 10m }
        - setWeight: 50
        - pause: { duration: 10m }

What you see: The blast radius of a bad build.

with and without the patternruns offline
# illustrative output
big-bang deploy:   bad build -> 100% of 10,000,000 monthly checkouts at risk
canary at 1%:      bad build -> 1% of traffic for 10 minutes, then rolled back automatically

The trap: A canary too small to carry a signal looks healthy because it saw almost nothing.

canary with too little trafficruns offline
# illustrative output
traffic 20 requests/min x 1% = 0.2 requests/min  ->  2 requests in a 10-minute window
2 requests, 0 errors: "healthy"   ✗ proves nothing; use a larger slice, a longer window, or synthetic traffic

When to use it / when not: Use it where real traffic exists and a metric can judge it.

Pattern: Consumer-driven contracts

The problem: The payment team renames a field, all their tests pass, and the order service breaks in production.

the breakruns offline
# illustrative output
payment v2.4.0 response:  {"id": "p-91"}              (was {"paymentId": "p-91"})
order-service:            reads paymentId -> null -> NullPointerException on the next line   ✗ found in production

How it works: The consumer writes down what it relies on, and the provider's build checks it.

  1. Record: the order service's tests record the request it sends and the response fields it reads into a contract file.
  2. Publish: the contract goes to a broker (Pact Broker).
  3. Verify: the payment service's pipeline replays the contract against its own code.
  4. Gate: can-i-deploy asks the broker whether this provider version satisfies every consumer in production.
sequenceruns offline
order-service build:    test runs against a mock   -> writes order-service-payment-service.json   ✓
                        publish contract           -> Pact Broker
payment-service build:  verify contract against real code
                        rename paymentId -> id     -> ✗ "order-service expects paymentId"   (build fails before deploy)

The setup: The contract is a JSON file generated by the consumer's test; the shape below is illustrative of a Pact file.

order-service-payment-service.json (illustrative)runs offline
{
  "consumer": { "name": "order-service" },
  "provider": { "name": "payment-service" },
  "interactions": [
    {
      "description": "a charge request",
      "request":  { "method": "POST", "path": "/payments",
                    "body": { "orderId": "7c1e", "amount": 340.00 } },
      "response": { "status": 201, "body": { "paymentId": "p-91" } }
    }
  ],
  "metadata": { "pactSpecification": { "version": "3.0.0" } }
}
deploy gateruns offline
pact-broker can-i-deploy --pacticipant payment-service --version 2.4.0 --to-environment production
# prints a table of consumer versions checked and a verdict; the exact layout depends on the Pact CLI version

What you see: The failure moves from production to the provider's pipeline.

with the patternruns offline
# illustrative output
payment-service pipeline:  verification of pact order-service -> payment-service FAILED
                           response body: expected key "paymentId" but it was missing        ✗ before deploy

The trap: A contract that pins every field and exact value breaks on harmless changes, so teams stop trusting it.

too strictruns offline
# illustrative output
contract asserts  amount == 340.00  and the whole body, including fields the consumer never reads
provider adds field "currency"  -> contract fails   ✗ false alarm
# ✅ FIX: assert only what the consumer reads; consumers are tolerant readers and ignore unknown fields

When to use it / when not: Use it between teams that deploy independently.

Configuration, secrets, and who may call whom

Configuration that differs by environment — database addresses, feature flags, timeouts — lives outside the image: environment variables or mounted files in Kubernetes (ConfigMaps), or a config service such as Spring Cloud Config for values that must change at runtime.

Secrets — passwords, API keys, signing keys — live in a dedicated store (HashiCorp Vault, or a cloud secrets manager, or Kubernetes Secrets backed by an external store) and are injected at startup, never committed and never baked into images.

The reason is not only leakage: it is rotation. A secret that lives in a store can be rotated without a redeploy; a secret in an image cannot.

Pattern: Externalized configuration

The problem: Configuration and secrets baked into the image force a rebuild per environment and put passwords in every copy of the image.

baked-in imageruns offline
# illustrative output
$ docker run --rm order-service:1.8 cat /app/application.properties
spring.datasource.url=jdbc:postgresql://prod-db:5432/orders
spring.datasource.password=s3cret-prod-pw         ✗ anyone who can pull the image can read it

How it works: One image for every environment; the environment supplies the values at start.

  1. Build once: the image contains code and defaults, no environment values.
  2. Inject: Kubernetes passes values from a ConfigMap (plain settings) and a Secret (credentials, ideally backed by Vault or a cloud secrets manager).
  3. Rotate: change the stored secret and restart the pods; no rebuild.
same image, three environmentsruns offline
order-service:1.8  +  dev ConfigMap/Secret      -> dev-db
order-service:1.8  +  staging ConfigMap/Secret  -> staging-db
order-service:1.8  +  prod ConfigMap/Secret     -> prod-db

The setup: Environment variables map onto Spring properties by relaxed binding.

order-service Deployment (container env)runs offline
env:
  - name: SPRING_DATASOURCE_URL
    valueFrom:
      configMapKeyRef: { name: order-config, key: db-url }
  - name: SPRING_DATASOURCE_PASSWORD
    valueFrom:
      secretKeyRef: { name: order-db, key: password }

What you see: The image no longer contains the password.

with the patternruns offline
# illustrative output
$ docker run --rm order-service:1.8 cat /app/application.properties
spring.datasource.url=${DB_URL}       # no value baked in   ✓

The trap: Environment variables are read when the process starts, so changing the ConfigMap or Secret does not reach pods that are already running.

stale configurationruns offline
# illustrative output
14:00  kubectl edit secret order-db      (password rotated)
14:05  running pods still hold the old password in their environment   ✗ connections fail at the next re-auth
# ✅ FIX: restart the Deployment after rotation (kubectl rollout restart), or use a secrets mechanism that reloads

When to use it / when not: Always for secrets; for configuration whenever it differs by environment.

Inter-service security in 2026 is built on three pieces.

Mutual TLS (mTLS) means both sides of every connection present a certificate, so service A knows it is really talking to payment and payment knows the call really came from A — a service mesh issues and rotates these certificates automatically, which is the strongest practical argument for a mesh.

OAuth 2.0 is the standard protocol for issuing access tokens, and OpenID Connect (OIDC) is the identity layer on top of it; in practice the gateway validates the user's token, and each internal call carries either that token or a short-lived service token so the callee can enforce "who is asking" at every hop, not just at the front door.

That "at every hop" is what zero trust means: no call is trusted because of where it came from on the network; every call is authenticated and authorised on its own.

Spring Security's resource-server support validates JWTs (JSON Web Tokens, the self-contained signed tokens OAuth usually issues) with a few lines of configuration, and the drill's design questions ask you to combine these three pieces into a coherent scheme.

Boardroom translation

Microservices are a speed purchase, and the price is paid in operations. The pitch to a leadership team is never "microservices are modern".

It is: "Today every release needs four teams in one room and ships twice a week; three of our five biggest incidents this year came from a change in one area breaking another.

Splitting along the four business domains we already have lets each team ship daily, and isolates a failure in recommendations from checkout.

The cost is real: a platform team of three to run tracing, deploy automation, and the message broker, and roughly six months where velocity dips while boundaries settle.

" Then the number that makes the decision: if checkout availability moves from 99.5% to 99.9% because a slow non-critical dependency can no longer take it down, that is about 35 hours a year of restored uptime — at $40,000 an hour of checkout revenue, $1.4 million a year against a platform team costing perhaps $600,000.

If the numbers do not work that way for your business, the honest recommendation is the modular monolith, and saying so is what earns the room's trust.

Quick reference — Operability

trace / span
A trace is one request's whole journey. A span is one hop in it. The trace id is what makes them one thing.
OpenTelemetry
The vendor-neutral standard for traces, metrics and logs. Instrument once.
correlation id
The same id in every log line of a request. Without it, logs from twelve services are twelve unrelated stories.
SLI / SLO / error budget
The indicator is what you measure. The objective is the promise. The budget is how much failure that promise still allows — and it turns “should we ship?” into a calculation rather than an argument.
Canary vs blue/green
Canary shifts a small share of real traffic and watches. Blue/green switches everything at once, and can switch back.
contract testing
Each consumer's expectations run against the provider's build. Catches the break before the deploy, not after.

06 · The primerScaling and Failure — How a Service System Falls Over, and How to Stop It

Services fail in patterns unique to distributed systems: a slow dependency that takes everyone down, a cache that expires all at once, and health checks that lie.

Here is the shape of almost every large platform outage. It is 09:00 on the busiest sales day of the year. Traffic is 3× normal, which capacity planning covered. One database replica used by the pricing service starts returning results in 800 milliseconds instead of 8.

Pricing's threads fill with slow queries; its response time climbs; the product-page service, which calls pricing on every request, starts timing out at its 1-second limit and retrying — tripling the load on pricing.

Pricing, now genuinely overloaded, gets slower; the product page's threads fill; the gateway's health checks to the product page start failing, so it pulls instances out of rotation, concentrating the same traffic on fewer instances, which fail faster.

Within six minutes every user-facing page is an error. The root cause was a single slow replica that could have been drained in thirty seconds.

This is a cascading failure: a local fault that spreads because each component's reaction to the fault makes it worse, and it is the single most important failure mode to understand in service systems.

The trace: The same outage as a timeline of one pool and its retries.

cascade timelineruns offline
# illustrative output
09:00  pricing replica 8 ms -> 800 ms             product page: 1000 req/s x 1 call to pricing
09:01  pricing pool full, timeouts at 1 s          product page retries: 3 attempts -> 3000 req/s hit pricing  ✗ load x3
09:03  product page threads full                   gateway health checks to product page fail
09:04  gateway pulls half the product-page pods     same traffic on fewer pods                                  ✗ fail faster
09:06  every user-facing page returns errors

Bridge: a queue is a queue, whether it is in a thread pool or in a city

You have seen the arithmetic in a thread pool. A server that processes 100 requests per second and receives 101 per second does not degrade by one per cent; its queue grows without bound, and latency climbs toward infinity.

Every component in a service system is such a server, and cascading failure is what happens when the queues connect: a slow downstream fills the upstream's pool, which fills the next one, all the way to the user.

The defence is to stop the queues from growing without bound, and there are three ways: refuse work you cannot finish (load shedding), slow the producer to the consumer's pace (backpressure), and make the callers stop retrying (breakers and retry budgets from section 03).

Load shedding means the server, on seeing that its queue is longer than it can serve within its latency objective, rejects new requests immediately with a 503 or 429 instead of queueing them.

A rejected request costs microseconds; a queued one costs a thread and, eventually, a timeout that the caller will retry anyway. Good shedding is prioritised: drop the recommendation calls before the checkout calls, drop anonymous reads before logged-in writes.

The concrete mechanism can be as simple as a bounded queue in front of the thread pool with a small size (Tomcat's server.tomcat.threads.max and server.tomcat.accept-count in Spring Boot), or as sophisticated as adaptive concurrency limits that measure latency and shrink the admitted concurrency when it rises.

Backpressure is the same idea travelling upstream: rather than a consumer buffering an unbounded amount from a fast producer, it signals how much it can take.

Kafka gives it structurally — a slow consumer simply falls behind, the lag metric grows, and the producer is unaffected; the queue is on disk in the broker rather than in memory in the consumer.

Reactive streams (Project Reactor, used by Spring WebFlux) give it inside a process through the request(n) protocol. HTTP does not give it at all, which is why HTTP chains need shedding and bulkheads.

Pattern: Load shedding

The problem: A server that queues every request it cannot serve ends up serving none of them in time.

Make the invisible visible: Concurrent requests in flight equal arrival rate times latency, so a slowdown alone can exceed the thread pool.

worked arithmetic and pool occupancyruns offline
in flight = rate x latency
normal:    1000 req/s x 0.008 s =   8 in flight        pool 200 threads: 8 busy, 192 idle
slow:      1000 req/s x 0.800 s = 800 in flight        pool 200 threads: 200 busy, 600 waiting  ✗
shedding:  admit at most 150, reject the rest at once   pool: 150 busy, extra requests get 503 in microseconds  ✓

How it works: Admit only as much work as can finish within the latency objective, and refuse the rest immediately.

  1. Bound: put a limit on concurrency or queue length in front of the work.
  2. Reject fast: above the limit, answer 503 (or 429) at once with a Retry-After header.
  3. Prioritise: reserve the last slots for checkout; drop recommendations and anonymous reads first.

The setup: Spring Boot bounds the Tomcat thread pool and accept queue (defaults: 200 threads, accept-count 100); a filter can add priorities.

application.ymlruns offline
server:
  tomcat:
    threads:
      max: 200            # default 200
    accept-count: 50      # default 100; a shorter queue means earlier, faster rejection
ShedFilter.java (sketch; imports omitted)runs offline
@Component
class ShedFilter extends OncePerRequestFilter {
    private final Semaphore slots = new Semaphore(150);

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        boolean critical = req.getRequestURI().startsWith("/checkout");
        // ✅ keep the last 50 slots for checkout; shed everything else first
        if ((!critical && slots.availablePermits() < 50) || !slots.tryAcquire()) {
            res.setStatus(503);
            res.setHeader("Retry-After", "1");
            return;
        }
        try { chain.doFilter(req, res); } finally { slots.release(); }
    }
}

What you see: The same overload, without and with shedding.

without the patternruns offline
# illustrative output
09:01  queue 600 deep   p99 38 s   timeouts 94%    every caller retries, load x3
with the patternruns offline
# illustrative output
09:01  admitted 150    p99 0.9 s   503 rate 72% of low-priority calls   checkout still 99% ok   ✓

The trap: Shedding without a retry budget: callers treat the 503 as a reason to retry immediately, and the rejected load comes straight back.

retry storm after a 503runs offline
# illustrative output
t=0.0  503   t=0.0  retry   t=0.0  retry   t=0.0  retry     ✗ 4x the load, no pause
# ✅ FIX: honour Retry-After, add jittered backoff, and cap retries per call (section 03)

When to use it / when not: Use it on every service that has a bounded pool.

Pattern: Rate limiting

The problem: One client (a buggy script, a scraper) sends 5,000 requests a second and uses the capacity every other customer needs.

How it works: Each caller gets a bucket of tokens that refills at a fixed rate; a request takes one token or is refused.

token bucket: capacity 10, refill 5 per secondruns offline
# illustrative output
t=0.0 s   tokens 10   10 requests arrive    ✓ all served, tokens 0
t=0.1 s   tokens 0.5  1 request arrives     ✗ 429 Too Many Requests
t=1.0 s   tokens 5    5 requests arrive     ✓ served, tokens 0

The setup: Spring Cloud Gateway has a Redis-backed limiter; the key resolver decides who "a caller" is.

gateway routeruns offline
spring:
  cloud:
    gateway:
      routes:
        - id: orders
          uri: lb://order-service
          predicates: [ "Path=/orders/**" ]
          filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 5
                redis-rate-limiter.burstCapacity: 10
                key-resolver: "#{@userKeyResolver}"   # one bucket per user

What you see: The noisy client is capped, and the others are untouched.

with the patternruns offline
# illustrative output
client scraper-7   5000 req/s   -> 5 served/s, rest 429
client alice          3 req/s   -> 3 served/s                ✓ unaffected

The trap: Keying the limit by IP address behind a corporate NAT, or keeping the counters in each instance's own memory.

limit that does not limitruns offline
# illustrative output
per-instance counters, 6 gateway instances, limit 100/min each  ->  a client can send 600/min   ✗
one IP shared by 4,000 office users, limit 100/min per IP        ->  the whole office is blocked ✗
# ✅ FIX: shared counters (Redis) and a key that identifies the real caller (API key, user id)

When to use it / when not: Rate limiting protects you from a caller; load shedding protects you from the total load.

The thundering herd and the caches that cause it

A thundering herd is many clients doing the same expensive thing at the same instant.

The classic trigger is a cache: 5,000 requests a second read the product catalogue from Redis, which is cheap; the cache key expires at 10:00:00.000, and for the next 40 milliseconds all requests miss and go to the database at once — 200 identical queries — which the database was never sized for.

The next trigger is a restart: 300 instances of a service come back after a deploy and all warm their caches simultaneously. The fixes are small and every senior candidate should have them ready.

Request coalescing (also called single-flight): when a key misses, one request fetches it and the others wait on that one result rather than each fetching; Caffeine's get(key, loader) does this inside one process, and a short lock in Redis does it across instances.

Jittered expiry: set the cache time-to-live to 300 seconds plus a random 0–30, so keys do not all expire together. Stale-while-revalidate: serve the old value while one background fetch refreshes it, so users never wait on a miss.

And the general rule, which is the same jitter idea as retries: whenever many machines might do a thing "at the same time", add randomness.

Caches in a service system stack up in layers, and it helps to name the layers and what each one is for. A client or CDN cache keeps static and semi-static responses near the user and cuts request volume before it ever reaches you.

A gateway cache stores whole responses for public, unauthenticated endpoints.

A local in-process cache (Caffeine) is the fastest possible — nanoseconds, no network — and the right home for small, hot, slow-changing data such as configuration or the price of the hundred best-selling products, at the cost that each instance warms separately and instances can briefly disagree.

A shared cache (Redis, Valkey) is a network hop away, roughly a millisecond, but every instance sees the same value, which matters for things like sessions and rate-limit counters.

The question to ask of every cache is "what happens when it is empty?", because that is the load the source of truth must survive.

Pattern: Cache-aside

The problem: Every read goes to the database, or a hot key expires and every request goes there at once.

thundering herd at expiryruns offline
# illustrative output
10:00:00.000  key "product:SKU-88" expires
10:00:00.000-.040   5,000 req/s x 0.040 s = 200 requests miss together
db: 200 identical SELECTs in 40 ms   (sized for about 5)   ✗

How it works: The application, not the cache, loads the data on a miss.

  1. Read: look in the cache; on a hit, return.
  2. Miss: read the database, store the value in the cache with a time-to-live, and return it.
  3. Write: update the database, then delete the cache key so the next read reloads it.
sequenceruns offline
read  hit:   app -> cache  ✓ value                                  (about 1 ms)
read  miss:  app -> cache  ✗ nothing -> db  ✓ row -> cache SET ttl -> return
write:       app -> db UPDATE ✓ -> cache DEL key

The setup: A jittered time-to-live spreads expiry, and Caffeine's loader call coalesces concurrent misses inside one process.

ProductCache.java (sketch)runs offline
// Shared cache (Redis): TTL 300 s plus a random 0-30 s so keys do not expire together
Duration ttl = Duration.ofSeconds(300 + ThreadLocalRandom.current().nextInt(31));
redis.opsForValue().set("product:" + sku, json, ttl);

// In-process cache (Caffeine): get(key, loader) runs the loader once per key; other callers wait for it
Cache<String, Product> local = Caffeine.newBuilder()
        .maximumSize(10_000)
        .expireAfterWrite(Duration.ofSeconds(300))
        .build();
Product p = local.get(sku, key -> repo.load(key));     // ✅ one database query, not 200

What you see: Database load at the moment of expiry.

without the patternruns offline
# illustrative output
10:00:00.000  db queries for SKU-88 in 40 ms: 200
with the patternruns offline
# illustrative output
10:00:00.000  db queries for SKU-88 in 40 ms: 1     (others waited for the one load)   ✓
              expiries across 1,000 keys now spread over 30 s instead of one instant       ✓

The trap: A write and a concurrent read race, and the cache keeps an old value until it expires.

stale value after a writeruns offline
# illustrative output
reader:  cache miss -> reads db (price 10)
writer:  UPDATE price = 12 -> cache DEL
reader:  cache SET price 10                      ✗ old value cached after the delete
# ✅ FIX: keep a short TTL as the safety net; for strict cases use versioned keys

When to use it / when not: Use it for read-heavy data that tolerates being a little stale.

Six minutes from one slow replica to a dead storefront db replica 8 ms → 800 ms pricing pool fills · queue grows product page times out · retries ×3 gateway health fails · pulls pods retries triple the load on the thing that is already slow fewer pods carry the same traffic → fail faster users: 100% errors Where the chain is cut at pricing: shed load bounded queue · 503 fast drain the slow replica at product page: breaker + fallback stop retrying · serve cached price bulkhead keeps threads free at gateway: shallow health check "am I alive" not "are my deps alive" never pull the whole fleet Each cut turns "slow and getting worse" into "degraded and stable" — the goal is a system that degrades in steps, not one that falls off a cliff.
Fig. E7.6 — Anatomy of a cascade. The two dashed loops are the feedback that makes it accelerate: retries that amplify load, and health checks that concentrate traffic. The three boxes below are where a well-designed system breaks the loop.

Pattern: Health checks (liveness and readiness)

The problem: A readiness check that asks "are my dependencies alive?" removes every instance at once when one shared dependency is slow, which is the gateway cut in the figure above.

table state: readiness checks the pricing databaseruns offline
# illustrative output
pod            readiness (checks pricing-db)   in Service endpoints
product-page-1 DOWN (db 800 ms)                no
product-page-2 DOWN (db 800 ms)                no
product-page-3 DOWN (db 800 ms)                no
-> 0 endpoints: every request gets an error, although all 3 processes are healthy   ✗

How it works: Two different questions, answered by two probes.

  1. Liveness: "is this process stuck beyond repair?" A failure makes Kubernetes restart the container. It must not look at dependencies.
  2. Readiness: "can this instance take traffic right now?" A failure removes the pod from the Service endpoints, without restarting it. Keep it shallow.
  3. Startup: a slow-booting service gets a startup probe, so liveness does not kill it before it has finished starting.

The setup: The Spring Boot actuator already exposes the two groups (enabled in application-observability.yml above); Kubernetes points its probes at them.

order-service container probesruns offline
livenessProbe:
  httpGet: { path: /actuator/health/liveness, port: 8080 }
  periodSeconds: 10
  failureThreshold: 3
readinessProbe:
  httpGet: { path: /actuator/health/readiness, port: 8080 }
  periodSeconds: 5
# ✅ keep the readiness group at its default (readinessState only)
# ❌ TRAP: management.endpoint.health.group.readiness.include=readinessState,db  (couples every pod to the database)

What you see: The same slow database, with a deep and a shallow readiness check.

with a deep readiness checkruns offline
# illustrative output
$ kubectl get pods -l app=product-page
NAME             READY   STATUS    RESTARTS
product-page-1   0/1     Running   0          ✗ all removed from rotation
product-page-2   0/1     Running   0
product-page-3   0/1     Running   0
with a shallow readiness checkruns offline
# illustrative output
$ kubectl get pods -l app=product-page
NAME             READY   STATUS    RESTARTS
product-page-1   1/1     Running   0          ✓ stay in rotation; a breaker and cached price handle the slow dependency
product-page-2   1/1     Running   0
product-page-3   1/1     Running   0

The trap: Putting dependency checks in the liveness probe: a database blip makes Kubernetes restart every pod, and the restarts add load.

restart stormruns offline
# illustrative output
14:02  database slow            liveness (checks db) fails on all pods
14:03  all pods restarted       cold caches, connection pools reconnecting   ✗ more load on the database
14:04  restarts keep going      RESTARTS 1, 2, 3 ...

When to use it / when not: Every service needs both probes, and each should be cheap.

Health checks that do not make things worse

A health check is an endpoint that Kubernetes or a load balancer polls to decide whether to send traffic to an instance. It is a common interview follow-up to the cascade scenario.

There are two kinds:

The trap is to make either one deep — to have the product page's readiness check call pricing, and pricing's call its database. Then when pricing is slow, every product-page instance reports unready at once, the gateway removes all of them, and the platform has amputated a service that could have served cached data.

Make the invisible visible: the same slow pricing database under a deep readiness check and under a shallow one.

readiness traceruns offline
# illustrative output
DEEP readiness (product-page checks pricing, pricing checks its DB)
  pricing DB slow  -> pricing /ready ✗ -> product-page /ready ✗ (all 6 pods)
  gateway: 0 healthy backends -> 503 on every product page          ✗
SHALLOW readiness (own pool only), pricing behind a breaker
  pricing DB slow  -> product-page /ready ✓ (6 of 6 pods)
  breaker OPEN     -> cached prices served                           ✓

The rule has three parts:

  1. Liveness checks test only the process itself (can it answer at all?).
  2. Readiness checks test only what the instance needs to start serving (is its own connection pool up?).
  3. Downstream health is handled by circuit breakers inside the service, not by removing the service from rotation.

Spring Boot exposes /actuator/health/liveness and /actuator/health/readiness separately for exactly this reason, and by default neither includes downstream HTTP calls.

Scaling out, and the first steps toward more than one region

Horizontal scaling — more instances behind a load balancer — works only for stateless services, meaning no request depends on which instance served the previous one.

Session state goes to Redis or into a signed cookie; file uploads go to object storage; anything an instance remembers is a scaling limit.

Kubernetes's Horizontal Pod Autoscaler adds instances when CPU, memory, or a custom metric (queue depth, requests per second) crosses a threshold; Chapter E10 covers the mechanics.

The database is the part that does not scale this way, which is why the patterns in section 04 push read traffic into per-service read models and caches, and why the hottest write paths get their own service with its own database.

Kafka scales by partitions: a topic with 12 partitions can be consumed by at most 12 instances of one consumer group in parallel, so partition count is a capacity decision made up front and painful to change later.

Multi-region deployment is where the theory from the Distributed Systems primer stops being theory.

Two regions 80 milliseconds apart cannot both accept writes to the same row without either a coordination round trip on every write (which costs the 80 milliseconds and fails when the link is cut) or conflicts to resolve later.

The practical answers, in increasing order of difficulty:

  1. Active–passive: one region serves all writes and the other holds a replica and takes over on failover (minutes of downtime, small data loss window equal to replication lag).
  2. Active–active with data partitioning: each customer's data lives in one home region and requests are routed there, so no row is ever written from two regions.
  3. True multi-master with conflict resolution: only a few workloads (shopping carts, counters, collaborative documents) can tolerate it, and it should be answered in an interview with "only if the data model allows last-writer-wins or a merge, and here is why ours does or does not".
failover timelineruns offline
# illustrative output: active-passive failover
region A primary, replica in B, replication lag 2 s
t=0      region A fails                             ✗
t=0      last 2 s of writes not yet replicated      ✗ the known loss window
t=+4 min region B promoted, writes resume           ✓

The event stream helps here: Kafka's MirrorMaker 2 or a cloud equivalent replicates topics across regions, so a service in the second region can build its read models from the same events.

Choosing the defence for a given overload or failure pattern
SymptomReach for…Because…
A slow non-critical dependency is eating the caller's threadsTimeout + bulkhead + breaker with a fallbackThe dependency must be allowed to be slow without the caller noticing; cap its share of threads and stop calling it while it is down.
A service's queue grows without bound under a traffic spikeLoad shedding with a bounded queue; prioritised rejectionServing a fraction of requests fast beats serving all of them late; late responses get retried anyway.
A recovered service gets knocked over again the moment it returnsRetry budgets, jittered backoff, breakers that half-open slowlySynchronised retries are a self-inflicted denial of service; spreading them out lets the service warm up.
Database load spikes every N minutes, exactly on cache expiryJittered TTLs, single-flight loading, stale-while-revalidateThe herd forms because expiries and misses align; randomness and coalescing break the alignment.
A slow dependency causes the whole fleet to be marked unhealthyShallow readiness checks; move dependency health into breakersRemoving instances that could serve degraded responses converts a partial failure into a total one.
A consumer cannot keep up with a producerBackpressure through the broker; scale consumers up to the partition countBuffering in memory turns lag into an out-of-memory crash; the broker's disk is the right buffer.

One example per row:

🧠 Brain power

Before the drill: a service has 200 request threads, a 2-second read timeout on a dependency, and no bulkhead. The dependency stops responding entirely (every call waits the full 2 seconds). The service normally receives 150 requests per second, of which 40% call the dependency. How long until the service has no free threads? And with a bulkhead of 20 on that dependency, what happens instead?

Reveal the answer

Without a bulkhead: 60 requests per second (40% of 150) each hold a thread for 2 seconds, so at steady state 120 threads are parked on the dependency, and the other 90 requests per second share the remaining 80 threads.

thread occupancyruns offline
# illustrative output (200 threads; 60 rps call the dependency, 2 s each)
no bulkhead   t=0 s: 0 parked   t=1 s: 60 parked   t=2 s: 120 parked, 80 threads left   ✗
bulkhead 20   t=2 s: 20 parked, 40 rps fail fast to the fallback, 180 threads free         ✓

That already works only if those requests finish in under about 0.9 seconds each; any slowness elsewhere and the pool is exhausted within a few seconds, taking the 60% of traffic that never needed the dependency down with it.

With a bulkhead of 20: at most 20 threads can ever be inside the dependency call; the other 40 dependency-calling requests per second fail instantly to the fallback, and 180 threads remain free for the 60% of traffic that does not need the dependency at all.

The service stays up in a degraded state — and that is precisely the definition of a bulkhead doing its job. The follow-up an interviewer wants: the breaker then opens within the first sliding window, so even those 20 threads are freed after a few seconds.

07 · DrillDecomposition & Communication — Q1–Q40

The first forty questions are where a senior round establishes whether you understand the trade rather than the vocabulary. They drill why systems get split, where the cut goes, and then the mechanics of a call across the network: timeouts, retries, idempotency, breakers, bulkheads, gateways and meshes, and finally the messaging side with Kafka. Every answer is written to be said aloud. Say yours first, then reveal.

Drill · Boundaries and decomposition

These questions test whether you can state the one real reason to split, price the costs honestly, and find a boundary that will still hold in two years.

Q1. "What is the actual reason to adopt microservices? Not the list — the one that matters."

Reveal answer

The real test Whether you lead with team independence or with technology.

Strong answer The reason is independent deployability: one team can change, test, and release its part of the system without coordinating with any other team.

Everything else usually listed — scaling one hot component, using a different language, isolating a crash — is real but secondary, and each of them can be had more cheaply in other ways.

A concrete example makes the point: a company with 60 engineers in a monolith deploys twice a week because every deploy carries everyone's changes and everyone must be ready; the same company with twelve services deploys forty times a day because each team ships when it is ready.

That shift in release cadence is what the architecture buys.

If the organisation does not have multiple teams that need to move at different speeds, the architecture buys nothing and costs a great deal.

  • Network calls: every in-process call becomes a network call that can time out or duplicate.
  • Sagas: the single transaction becomes a saga.
  • Pipelines: one deploy pipeline becomes twelve.

Picture it The same week of finished work under one shared deployable and under independent services, so you can see what the release cadence is actually buying.

The setup: Orders, Payments and Shipping each have a team, and the split changes what one line of code means.

one line, two meaningsruns offline
// Monolith: in-process call
reservation = inventory.reserve(orderId, sku, qty);        // nanoseconds, cannot time out

// Services: the same line now crosses a network
// ❌ TRAP: new failure modes appear: timeout, duplicate delivery, partial failure
reservation = inventoryClient.reserve(orderId, sku, qty);  // about 1-5 ms, can fail

Make the invisible visible: Release lanes for one week, with the wait made explicit.

release lanesruns offline
# illustrative output
MONOLITH (one artifact, one release train)
Mon  Orders   change merged            ✓ ready
Tue  Payments change merged            ✗ regression test red
Wed  Shipping change merged            ✓ ready
Thu  release held for Payments fix, then all three ship together
     Orders waited 3 days              ✗

SERVICES (one pipeline per service)
Mon 10:02  order-service merged        -> pipeline ✓ -> prod 10:19 ✓
Tue 14:30  payment-service red         -> only payment-service waits ✗
Wed 09:15  shipping-service merged     -> prod 09:31 ✓

What you see: A deploy report per service, taken from the pipeline, is the evidence that independence is real.

deploy reportruns offline
# illustrative output
service            deploys/week   needed another team?
order-service            20       no
payment-service          14       no
shipping-service          3       yes (waited for a new Inventory API)

Why: The release cadence improves only where a team can ship without anyone else; the network cost in the first block is paid on every call whether or not that happens.

Land it I would say microservices are an organisational tool with a technical cost, and I only pay the cost when the organisational problem is real.

Likely follow-ups
"How would you prove to me that a team actually has independent deployability, rather than just saying it?"

I would measure it, not assert it. There are three checks.

  1. Deploy frequency: the first number is deploy frequency per service, taken from the pipeline: if the order service ships on its own twenty times a week while nobody else is involved, that is independence.
  2. Coordination steps: the second is the share of deploys that needed a coordination step — a change-approval meeting, a second team's sign-off, a release note that lists three services together.
  3. The afternoon test: the third is a simple test: pick a service and ask whether a one-line change could reach production this afternoon with only that team awake.

If the honest answer includes "we would have to check with the platform team first" or "we usually wait for the Thursday train", the architecture has services but not the property that justifies them.

I would also look at the contract tests: a team that can deploy alone has consumer-driven contract tests that tell it, before merge, whether the change breaks anyone.

"What does the architecture cost in concrete numbers, not just in principle?"

The costs I have seen are measurable. A network call inside a data centre is roughly half a millisecond to a few milliseconds where an in-process call is nanoseconds, and a typical request that fans out to five services now has five chances to time out.

The single database transaction becomes a saga with compensations, which is typically three to five times the code of the original method.

Each service needs its own pipeline, dashboards, alerts, and a place in the on-call rotation, which in practice is about one platform engineer for every eight to ten services.

Debugging moves from a stack trace to a distributed trace, so you need a tracing backend and its storage. And availability multiplies: three services at 99.9% in series give the user 99.7%, which is about 26 hours a year rather than 9. Those are the bills the release cadence has to pay for.

The availability arithmetic from the last sentence, line by line.

availability arithmeticruns offline
0.999 x 0.999 x 0.999 = 0.997          three services in series
0.3% of 8,760 h/year  = about 26 h     (one service alone: 0.1% = about 9 h)
"Isn't independent scaling also a real reason? A hot search component, say?"

It is real, but it is usually the cheaper problem to solve another way.

A monolith can be deployed as several identical copies behind a load balancer with different routing rules, so the search endpoints go to a pool of twenty instances and the admin endpoints to two, all running the same build.

That gives independent scaling without a network boundary inside the code. Where scaling genuinely needs a separate service is when the hot component wants different hardware — a memory-heavy index, a GPU, a different runtime — or a different data store.

So I would put scaling in the list of secondary benefits: it can tip the decision for one specific component, but it does not justify splitting the whole system into twelve.

The test I apply is whether the scaling need is for one component or the whole thing; one component may earn its own service, the rest stays together.

"If a company has six teams and a monolith deploying twice a week, what would you do first — split it, or something cheaper?"

Something cheaper first, and I would say so. Twice a week with six teams is usually a pipeline and testing problem, not an architecture problem: a slow test suite, manual regression, and a release manager.

I would attack that directly — parallel test execution, feature flags so unfinished work can merge safely, trunk-based development, and automated deploys — and I have seen that alone take a monolith to daily deploys within a quarter.

In parallel I would enforce module boundaries inside the monolith, so that when a team genuinely needs its own cadence, its module can be extracted mechanically.

Only if, after that, a specific team is still blocked by other teams' readiness would I extract that team's module into a service. The order matters because splitting a monolith with a slow pipeline gives you twelve slow pipelines.

Q2. "Explain 'bounded context' in plain words and tell me how you would use it to decide where a service boundary goes."

Reveal answer

Strong answer A bounded context is a part of the business inside which each word has exactly one meaning. The word "customer" is the classic example.

To sales a customer is a lead with a pipeline stage; to billing it is an account with a payment method and a balance; to shipping it is a name and an address.

Those are three different objects that share a name, and forcing them into one Customer table is how monoliths tangle: every team adds columns, and a change made for shipping breaks a report for billing.

I use the idea in three steps.

  1. List the nouns the business uses.
  2. Find the split: look for where the same noun means different things or is owned by different people, and draw the boundary there.
  3. Translate at the border: each side keeps its own model.

A boundary drawn this way tends to be stable because the business meaning behind it is stable.

A boundary drawn along a technical layer — a "validation service" — or along a shared noun that every request needs is the kind that becomes the bottleneck everyone is blocked on.

Picture it One noun, "customer", as it appears in three bounded contexts on the order platform, and what a single shared table does to them.

Make the invisible visible: Three contexts, each with its own model of the same customer id 42.

one id, three modelsruns offline
SALES              BILLING                  SHIPPING
lead               account                  recipient
 id 42              id 42                    id 42
 stage=NEGOTIATION  payment_method=card_9    name, address
 owner=rep_7        balance=-120.00          phone

The trace: The same two changes against one shared Customer table, then against separate models that translate at the border.

change traceruns offline
ONE shared Customer table
 shipping adds address_line3             -> billing export breaks    ✗
 billing renames balance                 -> sales report breaks      ✗
PER-CONTEXT models
 shipping adds a field in its own model  -> others unaffected        ✓
 CustomerEmailChanged {id:42, email}     -> each side maps it itself ✓

Why: A boundary placed where the meaning of the word changes is stable because the business meaning behind it is stable. The primer block is Pattern: Bounded Context.

Land it The test I apply is whether the two sides could change their internal model without telling each other; if not, it is one context and should be one service.

Likely follow-ups
"Two bounded contexts both need the customer's email address. Who owns it, and how does the other one get it?"

One context owns the field as the source of truth — usually the one where the email is entered and verified, which is the account or identity context.

The other context does not query it on every request; it keeps its own copy of the fields it needs, populated from an event such as CustomerEmailChanged.

That copy is part of the second context's own model and it may hold only the fields it cares about, in the shape it needs.

The important point is that the copy is allowed to lag by the event delay and the second context is designed to tolerate that. The alternative — a shared customer table both contexts read — recreates the coupling the boundary was meant to remove.

So the rule is one owner, one event stream, many local copies, and an explicit translation step at each boundary so a change to the owner's model does not leak into the consumer's.

The email copy in the billing context after one change, with offsets.

event timelineruns offline
# illustrative output
account  offset 311  CustomerEmailChanged {id:42, email:"new@shop.example"}   owner commits ✓
billing  copy(42).email = "old@shop.example"   until it consumes offset 311   (lag 1.2 s) ✓ tolerated
billing  consumes 311 -> copy(42).email = "new@shop.example"                          ✓
"How do you find bounded contexts in a real codebase where nobody drew them?"

I start with people rather than code. I ask who gets paged for what, who approves which changes, and which teams argue about which tables — the arguments mark the boundaries.

Then I go to the language: I sit in on a sales stand-up and a billing stand-up and note where the same word means different things; that is a boundary.

In code, I look at the change history: files that change together in the same pull requests over a year belong together, and a table written by three different modules is contested ground. Tools such as code-ownership analysis on the git log make this visible.

I also run an event-storming session — a workshop where people from the business write down the events that happen in the domain on sticky notes and group them — because the groups that emerge are usually the contexts.

None of this is precise, but it converges, and a boundary drawn this way survives contact with the next feature.

"What happens if you draw the boundary wrong and find out a year later?"

The cost depends on which side of the data you got wrong.

If two services turn out to be one context — they always change together and one cannot act without calling the other — the fix is to merge them, which is mostly mechanical: one codebase, one database, and the network calls between them become method calls.

That is a few weeks. If one service turns out to contain two contexts, the fix is to split it, which is the expensive direction because it means migrating data and introducing events where there were joins.

The practical lesson is that I err on the side of larger services and fewer boundaries early, because merging is cheap and splitting is expensive.

I also keep the boundary inside the code visible as a module before I make it a network boundary, so that being wrong costs a refactor rather than a migration.

"Give me an example of a boundary that looks right but is actually wrong."

The classic is the "product service" in retail. Everyone needs a product, so it looks like a natural shared owner.

But the catalogue team's product is a name, a description, and images; the pricing team's product is a SKU with a price list; the warehouse's product is a barcode with dimensions and a bin location; and search's product is a document with facets.

Making one service own all of that means every team's change goes through one team, and every request in the platform calls it synchronously, which is the fan-in failure from the user-service scenario.

The right shape is that each context owns its own view of the product, keyed by a shared product id, and the catalogue context publishes changes that the others consume.

The tell that a boundary is wrong is a service that everyone calls and that several teams want to change at once.

Q3 · Scenario. "A company split its monolith into 14 services two years ago. Deploys still need four teams on a call, and a release train runs every second Thursday. What went wrong, and what would you look at first?"

Reveal answer

The real test Whether you can name the distributed monolith and diagnose it from the symptom rather than the architecture diagram.

Strong answer The symptom — a release train and multi-team deploys — says the services are not independently deployable, which means the company has a distributed monolith: the costs of a network between components with none of the benefits. I would collect evidence in this order.

First, the dependency graph of synchronous calls: if most requests fan out through five or more services in sequence, changes ripple.

Second, shared databases or shared libraries containing business logic: if two services read the same tables, or a "common-domain" jar has to be bumped in every service for each change, the boundary is not real.

Third, API versioning practice: if every change is a breaking change deployed in lockstep, nobody is writing backward-compatible contracts.

The likely causes, ranked:

  1. Wrong boundaries: cut along technical layers or shared nouns.
  2. A shared database.
  3. No contract testing, so teams coordinate deploys out of fear.

The fix is not more services. It has four parts.

  • Merge services that always change together.
  • Own data: move each remaining service onto its own data.
  • Compatibility: require backward-compatible changes for one release.
  • Contract tests: introduce consumer-driven contract tests so teams can deploy alone with confidence.

Picture it The call graph and the deploy history of a distributed monolith on the order platform, and the same change after the boundaries and contracts are fixed.

Make the invisible visible: The graph you would draw from traces, with the lockstep couplings marked.

call graphruns offline
# illustrative output
checkout -> order -> pricing -> inventory -> payment -> shipping
            depth 6, every hop synchronous
order, inventory, shipping ----> shared orders_db   (3 writers, 1 schema)
common-domain.jar 4.2 is pinned in all 6 services

The trace: One new field on the order response, and everything it drags along.

one-field changeruns offline
order-service adds field discountCode
 1. checkout must read it           -> deploy together             ✗
 2. common-domain.jar 4.2 -> 4.3    -> bump in all 6 services      ✗
 3. new column in shared orders_db  -> inventory reads that table  ✗
 4. four teams on a call            -> waits for the Thursday train ✗

What you see: Deploys cluster on one afternoon instead of spreading out.

deploys per dayruns offline
# illustrative output
Thu 14:00-16:30   checkout order pricing inventory payment shipping  (all 6)
other days        0 or 1 service

The fix: Expand and contract, plus consumer-driven contract tests (Pattern: Consumer-driven contracts), so each step ships alone.

deploys after the fixruns offline
# illustrative output
Tue 10:05  order-service adds discountCode, keeps the old field   ✓ alone
Wed 11:40  checkout starts reading discountCode                   ✓ alone
next week  order-service removes the old field                    ✓ alone

What you see now: Each change is its own deploy on its own day, so the release train has nothing left to carry.

Land it A release train is a diagnosis, not a process choice — it tells you the boundaries are wrong, and I would fix the boundaries before touching the pipeline.

Likely follow-ups
"You merged the services that always change together and it still needs a release train. What next?"

Then the coupling is in the contracts, not in the code layout. I would look at how API changes are made: if a change to the order service's response requires the checkout service to deploy at the same time, nobody is practising backward compatibility.

The fix is a rule and a tool. The rule is expand-and-contract: add the new field alongside the old, deploy the producer, migrate consumers on their own schedule, then remove the old field one release later.

The tool is consumer-driven contract testing, for instance Pact, where each consumer publishes the shape it depends on and the provider's build fails if it breaks that shape.

With those two in place a team can deploy alone because the build has already told it nobody breaks. If the train persists after that, I would look at the shared database and shared business-logic libraries, which are the two other places lockstep hides.

The three steps of expand and contract on the order response, each its own deploy.

expand and contractruns offline
// Step 1 (expand): producer adds the new field and keeps the old one
record OrderResponse(long id, String status /* old, still sent */, String paymentState /* new */) {}
// Step 2: consumers migrate to paymentState on their own schedule
// Step 3 (contract): one release later the old field is removed
// ✅ FIX: no step needs another team to deploy at the same time
"How do you tell a distributed monolith from a healthy system on a dashboard, without reading the code?"

Three graphs. First, deploys per service per week: in a healthy system the services deploy at different rates and on different days; in a distributed monolith they deploy in clusters on the same afternoon.

Second, the call depth per request from the tracing system: if a typical request touches six or more services in sequence, changes ripple and latency is the sum of everything.

Third, the change-failure correlation: when one service's deploy is followed within an hour by an incident in another service, the two are coupled. I would also pull the incident postmortems and count how many name a second service as the cause.

Those four signals come from tooling the platform already has, and they give the diagnosis before anyone opens a repository.

"Why is the fix not just better automation of the release train?"

Because automating the train makes the coupling cheaper to live with, and the coupling is the problem.

A faster train still means fourteen services deploy together, so a bug in one rolls back all of them, a test failure in one blocks everyone, and a team that is ready on Monday waits until Thursday.

The architecture was adopted so that teams could move independently, and a train — however smooth — is the admission that they cannot.

There is a place for automation: once the boundaries are fixed and services can deploy alone, each service's own pipeline should be fully automated. But automating the wrong thing entrenches it, because once the train works well enough nobody has a reason to fix the boundaries.

I would rather spend the same effort on contract tests and data ownership, which remove the need for the train.

"Which of the fourteen services would you merge first, and how would you convince the teams?"

I would merge the pair with the strongest coupling signal: the two that appear together in the most pull requests and the most incidents, and that call each other synchronously in both directions. Bidirectional synchronous calls are the clearest sign of one context cut in half.

To convince the teams I would show them their own data — the co-change history, the joint incident count, the time they spent last quarter coordinating — and frame the merge as removing work rather than as a failure.

Merging is cheap: the two codebases become one repository with two modules, the network calls become method calls, and the two databases become one with two schemas. I would keep the module boundary enforced so the option to split again remains.

After one merge goes well, the second is easier because the argument has been made in practice.

Q4 · Design. "You are asked to plan the split of a 400,000-line e-commerce monolith. Which service do you extract first, and how do you choose?"

Reveal answer

Strong answer My assumptions: one database, several teams, and a business that cannot pause. The design principle is to extract first the piece that gives the most independence for the least coupling. I score candidates on three questions.

  1. Data: how many tables does it own that nothing else writes?
  2. Coupling: how few synchronous calls does it need back into the monolith to do its main job?
  3. Ownership: how clearly is it owned by one team with a distinct release need?

In most e-commerce systems the winner is something like notifications or search indexing: they consume events, own their own data, and nobody else needs to call back into them.

Extracting one of those first proves the platform pieces — the outbox, the message broker, tracing, the deploy pipeline — on a low-risk path.

What I would not do first is checkout or "the user service": checkout touches everything and is where the money is, and a user service becomes a synchronous dependency of every request.

The trade-off is that the first extraction is not the one that delivers the most business value; it is the one that delivers the most learning with the least blast radius.

After two or three low-risk extractions the team knows its tooling, and the higher-value cuts (orders, payments) can follow with a strangler approach.

Picture it A scoring table that ranks extraction candidates from the monolith, then the routing that makes the first cut reversible.

Make the invisible visible: Each candidate is scored on the three questions from the answer. The numbers below are illustrative.

Extraction candidates scored on the monolith (illustrative numbers)
CandidateTables only it writesSync calls back into the monolithOwner and release needVerdict
Notifications3 of 30One team, own cadenceExtract first
Search indexing2 of 20 (consumes events)One teamGood second
Payment capture2 of 31 to 2One teamNarrow slice, strangler
Checkout2 of 911Four teamsNot first
User service1 of 4Every requestUnclearNot first

The trace: How a strangler routing rule moves one capability and keeps the way back (Pattern: Strangler Fig).

strangler routingruns offline
request POST /pay  -> gateway rule
  flag payment_v2 = off (default)           -> monolith             ✓ old path
  flag payment_v2 = on for 5% of users      -> payment-service      ✓ new path
                                              shadow compare against the monolith's record
  mismatch found                            -> flag off in seconds  ✓ rollback

Why: The first extraction is chosen for learning and a small blast radius, and the flag is what makes a failure a rollback instead of a money incident.

Land it Extract for learning first and for value second, because a failed first extraction ends the whole programme.

Likely follow-ups
"The business says notifications are not worth the effort and wants checkout extracted first. What would you cut to make that safe?"

I would not cut the safety steps; I would cut the scope.

Checkout as a whole touches orders, payments, inventory, and pricing, so I would take the narrowest slice that has a real boundary — payment capture, for instance, which has one clear input, one clear output, and its own data.

I would extract that as a strangler: the monolith keeps its checkout flow, but the step that talks to the card processor is routed to the new service behind a feature flag, with the flag defaulting to the old path.

I would keep the platform pieces minimal — a synchronous call with a timeout and an idempotency key, no broker yet — and I would run the new path for a percentage of traffic with reconciliation against the old path's records.

What I would refuse to cut is the reconciliation and the flag, because without them a failure in the first extraction is a money incident rather than a rollback.

"How do you actually measure 'how many tables does it own that nothing else writes'?"

Two sources. In the database, I enable statement logging or use the query statistics view — pg_stat_statements in PostgreSQL — and group writes by table and by the application module that issued them; if the application tags connections with the module name, this is direct.

In the code, I search for every repository or data-access class that references the table and map it to the package that owns it. The result is a table-to-writers matrix.

Tables with one writer are clean; tables with several are the contested ones, and the count of contested tables a candidate touches is its coupling score.

I do the same for synchronous calls by instrumenting the module boundaries inside the monolith and counting calls per pair over a week of production traffic. This takes a few days and turns the extraction order from an opinion into a ranking.

"What is the strangler approach in mechanics, not in name?"

The strangler pattern means putting a routing layer in front of the monolith and moving one capability at a time behind it.

Mechanically: a request for a feature enters the gateway; a rule sends it to the new service if the feature flag is on for that request, otherwise to the monolith.

The new service is built, tested with shadow traffic — it receives copies of real requests and its answers are compared with the monolith's but not returned — and then switched on for a small percentage of users, then all.

The monolith's code for that feature is deleted only after the new service has served all traffic for a period.

Data follows the same shape: the new service either owns the data from the first day or reads it through the monolith's API until its own store is filled by a migration and change data capture.

Each step is reversible by flipping the flag, which is what makes it safe.

"What breaks in the first extraction that people do not expect?"

Three things, in my experience.

  1. Hidden readers: a report, a cron job, or an admin screen that reads the table directly and was not in anyone's inventory; it breaks the week after the cut, so I look for them in the database's query logs before extracting.
  2. Transaction assumptions: code in the monolith that used to update the notification record and the order in one commit now has a gap between them, and a crash in that gap produces an inconsistency nobody had before; this is where the outbox appears for the first time.
  3. Latency: a method that was called two hundred times in a loop is now two hundred network calls, and the page that took 50 milliseconds takes 3 seconds; the fix is a batch endpoint, which means the API has to be designed for the caller's access pattern rather than mirroring the old method. Each of these is a reason to extract something low-risk first.

The latency surprise from the third item, in numbers.

latency traceruns offline
BEFORE  loop 200 x in-process getStock()          about 50 ms
AFTER   loop 200 x network call, 15 ms each        3000 ms   ✗
FIX     one batch endpoint getStock(List<sku>)     about 25 ms   ✓ (illustrative)

Q5. "State Conway's law and give me one concrete way you would use it on purpose."

Reveal answer

Strong answer Conway's law says that a system's structure ends up mirroring the communication structure of the organisation that built it — three teams building a compiler produce a three-pass compiler.

The consequence for services is that a boundary holds only if there is a team on each side of it.

Using it on purpose, sometimes called the inverse Conway manoeuvre, means deciding the architecture you want and then shaping the teams to match, rather than hoping the code will resist the org chart.

Concretely: if I want the payment service to be a real, independently deployable boundary, I give one team full ownership of it.

  • Code: one team owns it.
  • Data: the database is theirs.
  • Operations: the on-call pager and the deploy button are theirs.
  • Access: no other team has commit rights.

I would also look for the reverse signal in an existing system: a service that three teams all modify is not a boundary, it is a shared library with a network hop, and a service nobody owns will decay into one.

The law also explains why platform-wide concerns need a platform team: if there is no team whose job is tracing and deploy tooling, every service team builds a slightly different version of it.

Picture it Who can change the payment code before and after the team shape is aligned with the boundary, shown with ownership and commit evidence.

Make the invisible visible: Ownership of one service, before and after.

ownership mapruns offline
BEFORE  payment-service   edited by team-checkout, team-risk, team-billing   ✗ nobody owns it
AFTER   team-payments --- owns ---> payment-service + payments_db + pager + deploy button   ✓

The setup: A single ownership rule in the repository makes the boundary enforceable.

CODEOWNERSruns offline
# CODEOWNERS
/payment-service/   @shop/team-payments

What you see: Commit authorship over 90 days, taken from the git log.

git shortlogruns offline
# illustrative output: git shortlog -sn --since=90.days -- payment-service/
BEFORE   team-checkout 41   team-risk 27   team-billing 19
AFTER    team-payments 83   (others: 0, changes arrive as pull requests)

Why: The code follows the communication lines, so a boundary with three teams writing to it behaves like a shared library with a network hop.

Land it I treat team structure as an architectural decision, because the code will follow the org chart whether I plan for it or not.

Likely follow-ups
"What goes wrong if you reshape the teams but not the code, or the code but not the teams?"

Reshape teams without the code and you get a team that owns a boundary that does not exist: they are responsible for "payments" but the payment logic is spread across three modules other teams also edit, so every change is a negotiation, and the team's on-call covers code they do not control.

Reshape the code without the teams and you get services with no owner: the code has a boundary, but five teams still commit to it, the boundary erodes within a few months because nobody defends it, and the service becomes a shared library with a network hop.

Conway's law says the two must move together. In practice I move the team first by a small margin: give the team ownership of the target module inside the monolith, let them tighten its boundary, and then extract it when they want to.

That order means the extraction is done by the people who will carry the pager for it.

What the git log looks like six months after the code was reshaped but the teams were not.

git shortlogruns offline
# illustrative output: git shortlog -sn --since=6.months -- payment-service/
   38 team-checkout
   31 team-risk
   22 team-billing
    9 team-payments      ✗ the boundary is eroding, the owner is a minority
"How many services should a team of six own, and what happens above that?"

Between one and three, in my experience. One is ideal when the service is substantial; three is workable when they are small and related.

Above that, the team's attention fragments: each service needs dependency upgrades, security patches, dashboard reviews, and on-call knowledge, and with six services the team spends most of its time on maintenance rather than features.

The tell is the age of the oldest unpatched dependency across the team's services, which grows with the count.

When a team is above three, I would either merge services that belong together or give the platform team a template and automation that removes most of the per-service upkeep — automatic dependency bumps, a shared dashboard generated from the template, standard alerts.

A service the team has not deployed in six months is a candidate to merge into a neighbour.

"What does a platform team own, concretely, and how big should it be?"

A platform team owns the things every service needs and no product team should build twice: the service template with timeouts, tracing, health checks, and metrics wired in; the deploy pipeline as a reusable definition; the message broker, the schema registry, and the tracing backend; the service mesh or shared client library; and the on-call tooling.

They treat the product teams as customers, with a roadmap and a support channel, and they measure themselves on how long it takes a new service to reach production — a good platform gets that to under a day.

Size is roughly one platform engineer for eight to ten services, so a company with forty services has a platform team of four to six.

Without that team, each product team builds a slightly different version of each piece, and the platform is the sum of fifteen incompatible opinions about how to do tracing.

Q6. "What is a modular monolith, what actually enforces the modules, and why might you recommend it over services?"

Reveal answer

Strong answer A modular monolith is one deployable program whose code is divided into modules with enforced boundaries: each module exposes a small public interface, owns its own tables (often its own schema), and talks to other modules through that interface or through in-process events, never by reaching into internals.

What enforces it is tooling, not convention.

In the Java world, Spring Modulith (2.x pairs with Spring Boot 4 as of 2026) does three things.

  • Derives modules from top-level packages.
  • Fails a test if one module imports another's non-public package.
  • Persists events published between modules in an event log so they are not lost on a crash — an in-process outbox.

ArchUnit does similar checks as plain unit tests.

I would recommend it over services when the organisation has clear domains but does not yet need separate release cadences or separate scaling: you keep one deploy, one database transaction, one stack trace, and one set of dependency upgrades, while the boundaries are already drawn.

The day a module's team genuinely needs to ship independently, its public interface becomes an API and its schema becomes a database, and the cut is mostly mechanical.

Picture it What a module boundary looks like in the package tree, what the verification test does when a module reaches into another's internals, and the fix. The primer block is Pattern: Modular Monolith.

The setup: Modules are the top-level packages; only the root package of each is public.

package layoutruns offline
com.shop.orders             <- public API (OrderService)
com.shop.orders.internal    <- private (OrderRepository, entities)
com.shop.payments           <- calls orders only through com.shop.orders
boundary violationruns offline
import com.shop.orders.internal.OrderRepository;   // ❌ TRAP: reaches into another module's internals

class PaymentService {
    OrderRepository orders;                          // compiles, but the boundary is gone
}

@Test void modulesAreRespected() {
    ApplicationModules.of(Application.class).verify();   // Result: the test fails the build
}

What you see: The verification failure names the offending module pair. The exact wording varies by version.

test outputruns offline
# illustrative output
Violations detected while verifying the application modules:
 - Module 'payments' depends on non-exposed type
   com.shop.orders.internal.OrderRepository within module 'orders'

The fix: Depend on the public service, or listen to an event, instead of the repository.

boundary respectedruns offline
import com.shop.orders.OrderService;                 // ✅ FIX: public API of the orders module

class PaymentService {
    OrderService orders;                              // in-process call, no network cost
}

What you see now: The same verify() test passes, and a pull request that crosses the boundary again fails before merge.

Land it It is the option that keeps the door to services open without paying the network tax before anyone needs it.

Likely follow-ups
"Show me what a Spring Modulith module boundary looks like in code, and what the test that enforces it does."

Each top-level package under the application's root package is a module: com.shop.orders, com.shop.payments. Types in the module's root package are public API; types in sub-packages such as com.shop.orders.internal are private to the module. Another module may inject a bean from com.shop.orders but not from com.shop.orders.internal.

The enforcing test is a few lines: ApplicationModules.of(Application.class).verify(), run as an ordinary JUnit test. It fails the build if a module references another's internal package, if there is a dependency cycle between modules, or if a module depends on one it has not declared as allowed.

The same object can generate documentation — a diagram of the modules and their dependencies — so the architecture is checked and drawn from the same source.

Cross-module communication is meant to go through published interfaces or through application events, which the library can record in an event publication table so they survive a crash.

"How do you keep one database from becoming the shared-table problem inside a modular monolith?"

Each module gets its own schema and its own database user, and the users are granted access only to their own schema. That makes cross-module table access a permission error rather than a code review question.

Inside the code, the module's repositories and entities live in its internal package, so another module cannot even import them.

When one module needs another's data, it either calls the other module's public service method — an in-process call, so there is no network cost — or it listens to an event the other module publishes and keeps a local copy.

Foreign keys across schemas are not allowed, because they are exactly the coupling that makes the eventual split painful.

The compromise I accept is that a single transaction can still span two modules when they are called in one request, which is convenient now and is the one thing that has to be redesigned as a saga on the day of the split.

"When does the modular monolith stop being enough? What is the trigger to split?"

The trigger is a team that is measurably blocked by the shared deploy.

Concretely, it is one of three things.

  • Release cadence: a module's team wants to ship several times a day and the monolith's test suite and release process make that impossible.
  • Different shape: a module needs a different runtime, hardware profile, or scaling shape from the rest.
  • Blast radius: a module's failure — a memory leak, a runaway thread pool — keeps taking down features that belong to other teams and process isolation would stop that.

Those are the three real reasons, and I want to see one of them on a graph before I split.

What is not a trigger is size on its own, a new engineering leader's preference, or the desire to use a different language for its own sake.

When the trigger appears, the split is mechanical if the module rules were kept: the public interface becomes an API, the events go onto the broker, and the schema moves to its own database.

"What about the event publication log — how does an in-process outbox help if there is no network?"

The failure it prevents is not a network failure but a crash between two in-process steps. When the orders module commits an order and publishes an OrderCreated event, the payments module's listener runs asynchronously in another thread.

If the process is killed after the commit but before the listener finishes, the event is gone and the order sits unpaid.

Spring Modulith's event publication registry writes a row per event-and-listener pair in the same transaction as the business change, marks it completed when the listener succeeds, and on restart republishes the incomplete ones.

So the guarantee is the same as the transactional outbox — at-least-once, in the same commit — but inside one process. The listener therefore has to be idempotent, exactly as a Kafka consumer would be.

The advantage is that when the module later becomes a service, the events and the idempotent listeners already exist and only the transport changes.

The event publication table across a crash, in the same transaction as the order insert.

event_publication tableruns offline
# illustrative output
event_publication   listener_id        event_type     completion_date
  row 7             PaymentListener    OrderCreated   NULL          <- process killed here  ✗
after restart: incomplete rows are republished -> PaymentListener runs -> completion_date set  ✓

Q7 · Scenario. "Every service in the platform calls the user service synchronously on every request to load the account. The user service had a bad deploy for six minutes and the whole platform was down. The user-service team says their SLO allows six minutes a month. Who is right?"

Reveal answer

The real test Whether you see the boundary problem behind the availability argument.

Strong answer Both statements are true and the design is still wrong. The evidence to collect: the fan-in — how many services depend on user synchronously — and what they actually need from it.

Almost always the answer is a few stable facts: is this account active, what is its tier, what is its id.

The cause of the outage is that a per-request synchronous dependency makes every caller's availability the product of its own and the user service's, so a 99.9% user service caps the whole platform at 99.9% before anything else fails. The fix has three options, cheapest first.

  1. Token: carry the needed facts in the signed access token the gateway already validated, so no call is needed.
  2. Cache: cache the account in each caller with a short time-to-live and serve the cached value when user is down.
  3. Events: copy the facts into each service by consuming "AccountChanged" events, so the data is local.

Prevention is a rule in the architecture review: no service may require a synchronous call to another service to handle its main request unless that call is truly part of the business operation. The user-service team's SLO is fine; the platform's dependence on it is not.

Picture it The blast radius of a synchronous per-request dependency on the user service, minute by minute, and the same outage after the callers no longer need it.

Make the invisible visible: Who calls whom, with the failed node marked.

topologyruns offline
gateway --> checkout  --> user-service  ✗ bad deploy
        --> order     --> user-service  ✗
        --> inventory --> user-service  ✗
        --> shipping  --> user-service  ✗
Blast radius: every service that loads the account on each request

The trace: Six minutes of outage as the callers see it, then with the token and a stale cache.

outage timelineruns offline
# illustrative output
          error rate: checkout  order  inventory  shipping
14:00  user deploy        0%      0%      0%        0%
14:01  user returns 500  98%     97%     99%       96%   ✗ platform down
14:06  rollback done       0%      0%      0%        0%

AFTER the fix: facts in the access token, 5-minute cache served stale when user is down
14:01  user returns 500    0%      0%      0%        0%   ✓ callers never needed it

Why: Availability multiplies: 0.999 for the user service times 0.999 for the caller is about 0.998, so a per-request dependency caps every caller. Related blocks are Pattern: Cache-aside and Pattern: Circuit breaker.

Land it The right fix is to make the user service unnecessary at request time, not to demand five nines from it.

Likely follow-ups
"You put the account facts in the access token. What happens when an account is suspended — the token still says active for an hour."

That is the real trade-off of carrying facts in the token, and it is handled by choosing what goes in and how long it lives.

I would put only slowly changing facts in the token — account id, tier, roles — and keep its lifetime short, fifteen minutes rather than an hour, with a refresh token to renew it.

For suspension, which must take effect fast, I would keep a small denylist of suspended account ids that the gateway checks: it is tiny, changes rarely, and can be pushed to every gateway instance within seconds through a cache or a compacted topic.

Operations that genuinely need the current state — a withdrawal, a purchase over a limit — go to the owning service synchronously, because those are the cases where staleness has a cost.

So the rule is that the token handles the common path, a denylist handles the urgent revocation, and a synchronous check is reserved for the few decisions where minutes of staleness matter.

"The cache option: what time-to-live, and what do you serve when the entry has expired and the user service is down?"

The time-to-live is a business decision I would make explicit: for account facts, one to five minutes is typical, because the facts change rarely and a five-minute delay in seeing a tier change is acceptable.

The important design is what happens on a miss during an outage.

I would use stale-while-revalidate behaviour: an expired entry is served immediately and a background refresh is attempted; if the refresh fails because the breaker is open, the stale entry keeps being served up to a hard staleness limit, say thirty minutes, and is marked as stale in the response for anything that cares.

Only a request with no cached entry at all — a user who has not been seen recently — fails, and for those I would decide per operation whether to deny or to allow with a default tier.

I would also make the cache a local in-memory one with a size limit rather than a shared Redis, because a shared cache is another synchronous dependency.

One cached account entry through the outage, with a 5-minute time-to-live and a 30-minute hard limit.

cache timelineruns offline
# illustrative output
14:00  miss -> user-service answers, cached tier=gold                         ✓
14:06  expired, user down, breaker OPEN -> serve stale (age 6 min, flagged)   ✓
14:31  age 31 min > 30 min limit -> evicted, only now does the request fail   ✗
"How would you enforce the 'no synchronous dependency on the main path' rule so it does not decay?"

With tooling, not just a review meeting.

First, the tracing system already knows every synchronous call between services, so a nightly job builds the dependency graph and flags any new edge into a small set of critical services — user, auth, config — that appears on a request's main path.

Second, the service template's HTTP client requires a declared dependency name and a fallback, so a call without a fallback fails to compile or fails a startup check.

Third, a fault-injection test in staging: once a week, the user service is made unavailable for five minutes and every service's error rate is recorded; a service whose error rate rises has a hidden dependency, and its team gets a ticket.

The rule is written down in the architecture review, but the graph and the test are what catch drift, because the person adding the fourth call to user in a new feature never thinks of it as an architecture decision.

"The platform team says caching is fine but events are over-engineering. Where do you draw the line?"

I would agree for most services and disagree for a few. Caching is the right answer when a service needs a few facts, tolerates minutes of staleness, and can survive an outage with stale data; that describes most callers.

Events earn their cost when a service needs the account data to do its main job offline — batch jobs that run at night when the user service may be under maintenance — or when the service needs to query on account attributes, such as "all orders for tier-gold customers", which a cache cannot answer.

It is also the right choice when the fan-in is large enough that even cache misses are a meaningful load on the user service. So the line is: cache by default, events for the two or three services whose need is data rather than lookups.

And the token option comes before both, because for many callers the three facts they need are already in the request.

Q8. "How big should a microservice be? Give me the wrong answers too."

Reveal answer

Strong answer The wrong answers are the ones measured in code: "a few hundred lines", "one entity per service", "rewritable in two weeks".

Those produce hundreds of tiny services whose combined call graph nobody can reason about, sometimes called nanoservices, and every business operation becomes a long chain of network hops. The right answer is measured in ownership and change.

A service should be as large as one team can own end to end — code, data, pager — and as small as it needs to be for that team to deploy without waiting on anyone.

It should contain the things that change together, which usually means one bounded context, and it should be able to do its main job without a synchronous call to another service.

In practice that gives services of several thousand to a few tens of thousands of lines, with a team of five to nine owning one to three of them.

A useful check is the opposite question: when should two services merge? These signals say they are one service cut in half:

  • They are always deployed together.
  • They are always changed in the same pull request.
  • They share a database.

Merging them is then the right move.

Picture it Why a chain of tiny services costs more than it looks, with the latency and availability arithmetic for eight hops on the order platform.

Make the invisible visible: One order operation as eight sequential network hops.

eight hopsruns offline
order -> pricing -> tax -> promo -> inventory -> payment -> fraud -> shipping
each hop about 5 ms network + work, each 99.9% available

The trace: The arithmetic, line by line.

worked arithmeticruns offline
latency       8 hops x 5 ms           = 40 ms   (was 5 ms in one process)
p99           sum of eight p99s       -> slower than any single p99
availability  0.999 ^ 8               = 0.992   (about 70 h/year of some hop down)
memory       8 runtimes x a few hundred MB floor each -> gigabytes before any work

What you see: The merge test from the answer, run on the pipeline and trace data.

merge signalsruns offline
# illustrative output
pair                co-deploys  co-change PRs  sync both ways  shared lib
pricing + promo        71%         64%            yes             yes
order + shipping       12%          8%            no              no

Why: None of this buys independence when the same team owns all eight, so the rows with high co-change are the ones to merge.

Land it Size by team ownership and change coupling, and be as willing to merge services as to split them.

Likely follow-ups
"What would you look at in an existing system to decide whether two services should be merged?"

Four signals from data the platform already has.

  1. Co-deployment: from the pipeline history, how often the two services deploy within an hour of each other; above half the time, they are coupled.
  2. Co-change: from the repositories, how often a pull request or a linked pair of pull requests touches both; the same threshold.
  3. Calls both ways: synchronous calls in both directions, from the tracing graph; a service that both calls and is called by the same neighbour on the main path is one context.
  4. Shared data: a table or a business-logic library both depend on.

If three of the four are present, I would propose the merge. I would also ask the on-call engineers, because the pair whose incidents always involve both is known to everyone who carries the pager, whether or not the dashboards show it.

"What is the concrete problem with nanoservices, beyond 'too many'?"

Three concrete problems. Latency: a business operation that touches eight nanoservices in sequence pays eight network hops, so a 5-millisecond operation becomes 40 to 80 milliseconds, and the p99 is the sum of eight p99s.

Availability: eight services at 99.9% in series gives 99.2%, which is about 70 hours a year of one of them being down during your request.

Overhead: each service has its own JVM or runtime, its own connection pools, its own memory floor of a few hundred megabytes, so a system that needed four gigabytes of compute needs twenty; and each service has its own pipeline, dashboard, and dependency-upgrade schedule that someone must maintain.

The debugging cost is the one that hurts most: a bug that would be one stack trace becomes a trace across eight services with eight log streams. None of this is buying independence, because the eight are usually owned by the same team anyway.

The per-service memory floor from the third problem, worked out for eight services.

memory arithmeticruns offline
# illustrative output
8 services x 300 MB runtime floor each = 2.4 GB before any request is served   ✗
1 service  x 300 MB runtime floor      = 0.3 GB
"A service has grown to 200,000 lines and one team of nine owns it. Is that a problem?"

Not by itself. The questions I would ask are the ownership and change ones, not the size one. Can the team still deploy it several times a day with confidence? Is the build and test time under fifteen minutes?

Does the team understand all of it, or are there corners nobody touches? Is the internal structure modular, so that a change in one area does not surprise another?

If those answers are good, 200,000 lines is fine, and a healthy large service is far better than the same code cut into ten services with the same team owning all ten.

If the answers are bad — the build takes an hour, half the code is unowned, deploys are scary — the first fix is internal modularity, and the second is to consider whether the team is really two teams with two release needs, in which case one split along that line is justified. Size prompts the questions; it does not answer them.

Q9 · Design. "Pricing rules are needed by checkout, the product page, and the promotions engine. Do you build a pricing service or a shared pricing library? Defend the choice."

Reveal answer

Strong answer I would ask two questions before choosing. Does pricing need data of its own that changes at runtime — price lists, campaign tables, currency rates? And must all three callers see the same price at the same instant?

If pricing is pure computation over inputs the caller already has, a shared library is right: it runs in-process at nanosecond cost, cannot fail on the network, and each caller upgrades on its own schedule.

The cost is version drift — checkout on 2.3 and the product page on 2.1 can show different prices — which I would manage with a deprecation window and a build check that fails on versions older than N.

If pricing owns data that changes constantly and must be consistent across callers, a pricing service is right, because the data has one owner and one place to change it.

The costs are a synchronous hop on the hottest path in the system and an availability dependency. I would pair the service with three protections.

  • Cache: a local cache in each caller.
  • Bulkhead: a cap on the threads pricing can hold.
  • Fallback: the last known price.

What I would not do is build a service for pricing "because everything is a service" and then have it read the product database directly; that is the worst of both.

Picture it The same checkout price calculation as a shared library and as a service, so the version-drift cost and the network cost are visible side by side.

Make the invisible visible: Version drift with a library: two callers, two library versions, one product.

version driftruns offline
# illustrative output
SKU-77, list price 50.00
product page   pricing-lib 2.1   shows 45.00   (10% promotion rule)
checkout       pricing-lib 2.3   charges 44.00 (12% promotion rule)   ✗ customer sees two prices

The trace: The same read as a service call, with the protection layers from the follow-up.

checkout -> pricingruns offline
checkout -> pricing   timeout 150 ms (pricing p99 is 20 ms)
  ✓ 18 ms   price 44.00, cache refreshed
  ✗ 150 ms  timeout -> breaker counts failure -> cached 44.00, marked "re-confirm"
payment step: re-price synchronously
  ✓ price confirmed -> charge
  ✗ pricing down    -> checkout fails closed, no charge at a stale amount

Works/Fails: The two options in short.

  • Works: a library for pure computation over inputs the caller already holds; a service for price lists and campaigns that change at runtime and must be the same for every caller.
  • Fails: a library carrying changing data (drift between versions, as above); a service that reads the product database directly (network cost with none of the ownership). See Pattern: Timeout and Pattern: Circuit breaker for the protection layers.

Land it Logic without state belongs in a library; state with one owner belongs in a service — and pricing is usually the second once campaigns exist.

Likely follow-ups
"You chose the service. Checkout calls pricing synchronously on the hottest path — what does that cost and how do you protect it?"

The cost is a network hop of a few milliseconds on every checkout and an availability dependency: checkout can only be as available as pricing. I would protect it in four layers.

A read timeout derived from pricing's measured p99 — if pricing answers in 20 milliseconds at p99, a 150-millisecond timeout.

A local cache in checkout keyed by product id and currency with a short time-to-live, refreshed on each successful call, which absorbs most calls during a pricing slowdown. A circuit breaker with a fallback to the cached price, marked as needing re-confirmation at payment.

And a bulkhead so pricing can hold at most a fraction of checkout's threads.

The fallback rule is strict: checkout may show a cached price, but it must re-price synchronously before charging, and if pricing is truly down at that moment the checkout fails rather than charging a stale amount. A wrong charge costs more than a lost sale.

"What if the requirement changes and pricing must also run in a mobile app offline?"

Then the computation part of pricing has to exist as a library after all, and the design becomes a hybrid.

The pricing service remains the owner of the data — price lists, campaign rules, rates — and publishes a versioned snapshot of that data as a compact file.

The library contains the rules engine and is embedded in the mobile app and in checkout; it takes a snapshot as input. The mobile app downloads the latest snapshot when online and prices offline from it, clearly marked as indicative.

Checkout on the server still calls the service for the authoritative price at payment time, so an old snapshot on a phone cannot produce a wrong charge.

The version drift problem returns — the app might have last week's snapshot — so the snapshot carries a version and an expiry, and the app refuses to price with an expired one.

This is the same shape as reference data: one owner publishes, everyone copies, and the authoritative decision stays with the owner.

What the app does with an expired snapshot.

snapshot expiryruns offline
# illustrative output
snapshot v42, expires 2026-11-20
2026-11-18 online   -> refresh to v43                                  ✓
2026-11-22 offline  -> v42 expired, app refuses to price, shows "price unavailable"   ✓ no stale charge
"How do you manage version drift of a shared library across twenty services in practice?"

Three mechanisms. First, automated dependency bumps: a bot such as Renovate or Dependabot opens a pull request in every consumer when the library releases, so upgrading is a click rather than a task someone remembers.

Second, a floor: the build fails if the library version is older than a declared minimum, which the library team raises with a deprecation window of, say, two releases or eight weeks; the check can be a plain Gradle or Maven rule.

Third, visibility: a dashboard, fed from each service's build metadata or its /actuator/info endpoint, showing which version each service runs, so the pricing team can see who is behind.

For pricing specifically I would also make the library log its version on every price calculation trace, so a customer-facing discrepancy can be traced to a version difference in minutes. The library must also follow strict semantic versioning, so a bump is safe to automate.

"Under time pressure, what would you cut from the service option?"

I would cut the fallback sophistication and the bulkhead, not the timeout or the idempotent re-price at checkout.

The minimal safe version is: a pricing service with one endpoint, a client with a short timeout and two retries, and a rule that checkout fails closed when pricing is unavailable. That loses some sales during a pricing outage but never charges a wrong amount.

The cache, the breaker, and the stale-price fallback for the product page can be added in the following sprint, because a product page that errors during an outage is a visible but recoverable problem.

What I would not cut is the ownership: the service owns its price data in its own store from the first day, because giving it a shortcut into the product database to save a week creates the coupling that costs months to remove later.

Q10. "When would you NOT use microservices, even if the team asked for them?"

Reveal answer

Strong answer I would push back in four situations.

  1. A small team — under roughly twenty engineers — because a team that size cannot own twelve services well, and the operational load of twelve pipelines, twelve dashboards, and one on-call rotation covering all of them will consume the capacity the split was meant to free.
  2. An unsettled domain: a product still finding its shape will redraw its boundaries every quarter, and moving a boundary between two services means migrating data across databases, whereas moving a package boundary is a refactor.
  3. No platform capacity: without someone owning tracing, the broker, deploy automation, and a service template, each team builds those badly and differently.
  4. A single tight transaction: a workload that is one — a ledger, an inventory allocation — where splitting forces a saga onto something that was correct for free in one database.

In each case the honest recommendation is a modular monolith with enforced boundaries, so that the split remains possible later.

I would say this to the team plainly, with the numbers: here is what we deploy today, here is what it would cost in people, and here is what we would get.

Picture it What twelve services cost a fifteen-person team in upkeep, and what a single-transaction workload loses when it is split.

Make the invisible visible: The recurring load of twelve services, as arithmetic.

upkeep arithmeticruns offline
12 services -> 12 pipelines, 12 dashboards, 12 dependency schedules, 1 on-call rotation
rule of thumb: 1 platform engineer per 8 services -> 12 / 8 = 1.5 engineers
1.5 of 15 engineers = 10% of the team, before any feature work

The setup: An inventory allocation that is correct for free in one database.

allocation.sqlruns offline
BEGIN;
UPDATE stock SET reserved = reserved + 2
 WHERE sku = 'SKU-1' AND available - reserved >= 2;   -- ✅ both writes or neither
INSERT INTO orders (id, sku, qty, status) VALUES (501, 'SKU-1', 2, 'PLACED');
COMMIT;

The trace: The same two writes once orders and stock are separate services with separate databases.

after the splitruns offline
orders_db     INSERT order 501 status=PENDING      ✓ committed
call inventory reserve(SKU-1, 2)                   ✗ timeout after 500 ms
stock_db      reserved = ?                         unknown: committed or not
state         order PENDING, stock unknown         ✗ needs a saga and reconciliation

Why: The split turned a free guarantee into a design problem. The alternative recommended in the answer is Pattern: Modular Monolith.

Land it The senior move is to buy the outcome the team wants — faster, safer releases — with the cheapest architecture that delivers it.

Likely follow-ups
"The team of fifteen insists. They say they will hire. What do you say?"

I would say that the architecture should follow the team that exists, not the one that is planned, because the hiring may take a year and the operational cost starts on the first day.

I would offer a path: build as a modular monolith now, with the module boundaries drawn where the future teams would sit, and agree on the trigger that turns a module into a service — a second team that owns it and needs its own release cadence.

That way the day the hires arrive, the split is a two-week job rather than a rewrite, and until then fifteen people run one deployable with one pipeline and one on-call rotation.

I would also show them the arithmetic: twelve services means twelve pipelines, dashboards, and dependency schedules, which is roughly one engineer's full time per eight services just in upkeep, before any features. Most teams accept that when they see it as a headcount number.

"Why is an unsettled domain such a problem for services specifically?"

Because moving a boundary between two services means moving data between two databases, and moving data is the most expensive operation in the system.

In a monolith, discovering that "reservation" belongs with "inventory" rather than with "orders" is a refactor: move a package, adjust some imports, keep the same tables.

Between services it means a new table in inventory's database, a backfill from orders' database, dual writes or change data capture during the transition, a new set of events, consumers updated to the new owner, and finally the deletion — weeks of work with reconciliation throughout.

A product that redraws its boundaries every quarter would spend most of its engineering on migrations. So the rule is that boundaries should be cheap to move until they are stable, and only stable boundaries should be made expensive to move by turning them into services.

The same boundary move in a monolith and between services.

moving a boundaryruns offline
MONOLITH  move package com.shop.orders.reservation -> com.shop.inventory    ✓ one commit
SERVICES  1 new table in inventory_db     2 backfill from orders_db
          3 dual writes or CDC            4 new events, consumers repointed
          5 delete the old table          weeks, with reconciliation at each step  ✗
"What does 'platform capacity' mean concretely — what is the minimum before services make sense?"

The minimum is that a new service can reach production with tracing, metrics, alerts, a pipeline, and a broker connection without the product team building any of it.

Concretely: a service template that generates a skeleton with health checks, structured logging with a correlation id, outbound clients with timeouts, and metrics exported; a pipeline definition that builds, tests, and deploys with a rollback; a tracing backend collecting spans from every service; a message broker with a schema registry and a policy for topics; and at least one person whose job is to keep those working.

Without that, every team makes its own choices, and the platform becomes fifteen ways to do tracing. I would want to see a second service reach production in under a day using only the template before I agreed the platform was ready for a third.

Drill · Synchronous calls: timeouts, retries, idempotency

This group tests the mechanics of a single network call: what can go wrong, what each tool protects against, and the arithmetic behind the numbers you set.

Q11. "REST or gRPC between internal services — how do you choose, and what does gRPC actually give you?"

Reveal answer

Strong answer gRPC is a remote-procedure-call framework that runs over HTTP/2 and encodes messages with Protocol Buffers, a compact binary format defined in a schema file.

Compared with JSON over HTTP/1.1 it gives five things.

  • Smaller payloads: often 3 to 10 times smaller.
  • One multiplexed connection instead of many.
  • Generated typed clients in every language.
  • Deadline propagation: a caller's remaining time budget flows to each callee.
  • Streaming in both directions.

I choose gRPC for chatty internal paths where latency and throughput matter and both sides are services I control.

I choose REST when the API is consumed by browsers or third parties, when human readability and cacheability matter, or when the team's tooling and debugging habits are HTTP-shaped.

The costs of gRPC are that browsers need a proxy such as grpc-web, binary payloads are harder to inspect on the wire, and it is still synchronous, so the same timeout, retry, and breaker discipline applies.

Two version facts: Spring Boot 4.x has first-class gRPC support through the Spring gRPC project (as of 2026), and Protocol Buffers' schema evolution rules — never reuse a field number, add fields as optional — are how gRPC APIs stay backward compatible.

Picture it The same product-detail call over REST and over gRPC, and what a plain layer-4 load balancer does to a gRPC client.

Make the invisible visible: The contract and the payload for the same call.

price.protoruns offline
message PriceReply {
  string sku = 1;
  int64 gross_cents = 5;
  reserved 2, 3;              // removed fields: numbers are never reused
}
payload sizesruns offline
# illustrative output
REST/JSON   40 KB   12 requests -> 12 HTTP/1.1 connections
gRPC/proto   9 KB   12 requests -> 1 HTTP/2 connection (multiplexed)

The trace: Why one long-lived connection becomes a load problem behind a layer-4 balancer.

connection pinningruns offline
BEFORE  client-A, client-B, client-C each hold 1 HTTP/2 connection to pod-1
        pod-1 480 rps    pod-2 10 rps    pod-3 10 rps    ✗ uneven
AFTER   client-side balancing over a headless Service (or an L7 proxy)
        pod-1 167 rps    pod-2 167 rps   pod-3 166 rps   ✓

Why: A layer-4 balancer balances connections, and gRPC puts all requests of a client on one connection. The call stays synchronous, so Pattern: Timeout still applies.

Land it The wire format is the smaller decision; whether the call should be synchronous at all is the bigger one.

Likely follow-ups
"How does a gRPC API stay backward compatible when a field changes meaning, not just when one is added?"

It does not, and that is the honest answer: Protocol Buffers protect the wire format, not the meaning. Adding a field with a new number is safe because old readers skip unknown fields and new readers see the default when it is absent.

Removing a field is safe if the number is marked reserved so nobody reuses it. But changing what field 4 means — from net price to gross price — is a silent break, because both sides parse it fine and one of them is wrong.

For a meaning change I add a new field with a new number and a new name, deprecate the old one in the schema comment, run both for a migration window, and remove the old one only when no client sends or reads it, which I can check from the server's metrics on which fields are populated.

The other invisible break is changing a field's type between incompatible wire types, such as string to int32; that is caught by a schema-compatibility check in CI, for example Buf's breaking rule set.

A meaning change done safely: a new number and a new name, with the old field deprecated.

price.proto (migration)runs offline
message PriceReply {
  int64 net_cents   = 4 [deprecated = true];   // old meaning: net price, still sent during migration
  int64 gross_cents = 5;                        // ✅ FIX: new number, new name for the new meaning
}
// ❌ TRAP: reusing number 4 for gross would parse fine on both sides and be silently wrong
"You said one multiplexed connection. Why is that a problem behind a plain load balancer?"

Because a layer-4 load balancer balances connections, and gRPC opens one long-lived HTTP/2 connection and sends every request over it. So a client with one connection sends all its traffic to one server pod for as long as that connection lives, which can be hours.

If five clients each pin to the same pod by chance, that pod takes all the load and the other nine idle. It also means a new pod added for scaling receives no traffic until a connection is re-established.

There are three fixes.

  1. Layer-7 proxy: one that understands HTTP/2 and balances individual requests, which is what a service mesh sidecar or an Envoy-based gateway does.
  2. Client-side load balancing: the gRPC client resolves all pod addresses through a headless Kubernetes service and round-robins across them.
  3. Connection recycling: setting MAX_CONNECTION_AGE on the server so connections are recycled every few minutes, which is a partial fix.

I check for the problem with a per-pod request-rate graph; uneven bars mean pinning.

"What happens to deadline propagation at the boundary where gRPC meets REST?"

It stops unless someone carries it across by hand. gRPC clients propagate the deadline automatically as the grpc-timeout header on each outbound call, computed from the remaining budget.

When a gRPC service then makes a REST call, nothing carries the deadline into the HTTP client, so that call uses its own configured timeout regardless of how much time is left.

The fix is a small piece of infrastructure: an interceptor that reads the remaining deadline from the gRPC context and sets the REST client's per-request timeout to the smaller of its configured value and the remaining budget, and on the REST side a filter that reads a deadline header and puts it into the request context.

I would put both in the service template. Without that, a chain that is mostly gRPC gets the benefit until the first REST hop, and the REST hop is the one that keeps working on a request the user abandoned.

"Give me a concrete number for what gRPC saved in a system you know."

The kind of numbers I have seen: a product-detail call that returned a 40-kilobyte JSON document became a 9-kilobyte protobuf message, and with HTTP/2 multiplexing the client that made twelve such calls per page went from twelve connections to one.

Serialisation time on the server dropped from around 3 milliseconds to under half a millisecond per response, which at a few thousand requests per second freed measurable CPU. The end-to-end p99 improved by roughly 20 to 30 milliseconds on a 200-millisecond page, which is noticeable but not dramatic.

The larger gain was in developer time: generated clients meant the four consuming teams stopped writing and maintaining their own HTTP client code, and a schema change broke the build rather than production.

I would present those honestly: gRPC is a real but moderate latency win and a large contract and tooling win, and it does nothing about the decision of whether the call should be synchronous.

Q12. "What are the two timeouts every HTTP client has, and how do you decide the values?"

Reveal answer

Strong answer The connect timeout bounds how long the client waits to open the TCP connection; the read timeout (sometimes called response or socket timeout) bounds how long it waits for bytes once connected.

A missing read timeout is the dangerous one, because a server that accepts the connection and then stalls holds your thread forever.

I set the connect timeout short — 200 to 500 milliseconds inside one data centre — because a healthy server accepts connections in microseconds, and a slow connect means the host or network is broken.

I set the read timeout from the callee's measured latency: take its 99th percentile under normal load and add a margin, so a service with a p99 of 80 milliseconds gets perhaps 500 milliseconds.

The read timeout has two ways to be wrong.

  • Too tight: healthy slow calls fail and get retried, adding load.
  • Too loose: a stuck dependency parks threads for seconds.

In Spring Boot 3.5+ and 4.x, spring.http.client.connect-timeout and read-timeout configure the shared RestClient builder.

I also make sure the caller's total budget is smaller than what its own caller will wait, so the timeouts nest inward rather than each layer waiting longer than the one above.

Picture it One HTTP call drawn as a timeline with all the timeouts that bound it, and how the timeouts nest from the user inward. The primer block is Pattern: Timeout.

The setup: Defaults for the shared client, set per dependency where it matters.

application.propertiesruns offline
spring.http.client.connect-timeout=300ms
spring.http.client.read-timeout=500ms
# per dependency, set in your own properties:
clients.pricing.read-timeout=500ms

Make the invisible visible: One call from checkout to pricing, in time order.

call timelineruns offline
t=0 ms    request waits for a pooled connection   (acquire timeout)
t=2 ms    TCP connect to pricing                  (connect timeout 300 ms)
t=3 ms    request sent
t=3..503  waiting for the first bytes             (read timeout 500 ms)
t=503 ms  ✗ read timeout fires, caller thread freed; pricing may still be working

The trace: The timeouts must shrink as you go inward.

nested budgetruns offline
# illustrative budget
browser gives up at         3000 ms
gateway timeout             2000 ms   ✓ smaller than the browser
checkout -> pricing read     500 ms   ✓ smaller than the gateway

Why: A missing read timeout lets a stalled server hold your thread forever, and a missing acquire timeout makes requests queue silently on an exhausted pool.

Going deeper There is a third timeout that shows up in incidents more often than the two named ones: the connection-pool acquire timeout.

Every HTTP client keeps a pool of open connections per host (Apache HttpClient's maxPerRoute, Reactor Netty's maxConnections), and when the pool is exhausted a new request waits for one to be released.

With no acquire timeout, a slow dependency that has all pooled connections busy makes every new request queue silently, and the thread dump shows threads waiting on the pool rather than on a socket.

I set the acquire timeout to roughly the read timeout, so a request that cannot even get a connection fails fast.

A fourth timeout is the write timeout for large request bodies, which matters for uploads.

Finally, a rule for choosing read timeouts on a path with a propagated deadline: the client's timeout is the minimum of its configured value and the request's remaining budget, never the configured value alone.

Land it The read timeout is a statement about the callee's real latency distribution, so I derive it from metrics and revisit it when the metrics move.

Likely follow-ups
"What happens when a read timeout fires — does the server stop working on the request?"

No, and that is a common surprise. When the client's read timeout fires, the client closes its side of the connection and throws, but the server has no idea unless it checks.

A servlet thread that is running a slow database query keeps running it to completion, writes a response nobody reads, and only then discovers the connection is closed.

So a timeout protects the caller's thread, not the callee's capacity, and a client that times out and retries doubles the callee's load rather than reducing it.

Making the server stop takes cooperation: the server reads a deadline header and checks it before expensive steps, a database query is issued with a statement timeout that matches the remaining budget, and reactive or virtual-thread servers can observe the connection reset and cancel.

Without those, the honest description of a read timeout is that it moves the waiting from your thread to theirs.

A timeout and a retry against a slow query, in time order.

timeout and retry traceruns offline
t=0      client sends GET /price         server starts a 4 s query
t=500    client read timeout ✗           client closes the socket, its thread is freed
t=700    client retries                  second query now runs next to the first, load doubles ✗
t=4000   first query finishes            writes a response to a closed socket, work wasted
"The dependency's p99 doubled after a release. Do you change your timeout?"

First I find out whether the doubling is the new normal or a regression.

If it is a regression, the right response is to have them fix it, and in the meantime my timeout will fire more often, my breaker may open, and my fallback will carry the load, which is exactly what those mechanisms are for.

If it is the new normal — a new feature that legitimately does more work — then my timeout was a statement about the old distribution and I revisit it, with two constraints: my own caller's budget still bounds it from above, and my thread pool's capacity bounds it from below, because a longer timeout means more threads parked per second of slowdown.

If I cannot raise it without breaking one of those, the conversation with the dependency team is about a faster endpoint or a batch call, not about my number.

I also make the timeout a runtime-adjustable property so this change is a config push, not a deploy.

"How do you set timeouts for a call that has a bimodal latency — 10 milliseconds usually, 2 seconds for a cold cache?"

A single number cannot serve both modes well, so I would separate them.

If the slow mode is rare and the caller can tolerate failure, I set the timeout for the fast mode — say 100 milliseconds — and let the cold-cache calls fail into a fallback; the dependency warms its cache from the attempt anyway, and the next call succeeds.

If the slow mode must succeed, I make the two modes different calls: a fast endpoint with a short timeout and, on a specific "cache miss" response, a second call to a slow endpoint with a long timeout, run on a bounded bulkhead so it cannot take more than a few threads.

The alternative is to have the dependency return a quick "not ready, retry after" response instead of doing the slow work inline, which turns the slow mode into an asynchronous warm-up.

What I would not do is set the timeout to 3 seconds for every call so the rare case works, because then the common failure mode — a stall — costs 3 seconds per thread.

"Where do the values actually live, and how do you stop a developer creating a client with no timeout?"

The values live in configuration, per dependency, with names that make the graph readable: clients.pricing.connect-timeout=300ms, clients.pricing.read-timeout=500ms.

In Spring Boot 3.5 and 4.x the global defaults for the auto-configured RestClient builder are spring.http.client.connect-timeout and spring.http.client.read-timeout, and I set those to conservative values so nothing is unbounded by accident.

To stop unbounded clients, the service template provides a single factory that requires a dependency name and looks up its timeouts, and an ArchUnit test fails the build if any code constructs RestClient, WebClient, or a raw HttpClient outside that factory.

I also add a startup check that walks the registered clients and refuses to start if any has a timeout above a ceiling, say 10 seconds, because a timeout of one minute is the same as no timeout under load.

Q13 · Scenario. "At 14:05 the checkout service stopped responding. CPU was 4%, memory normal, no errors in its logs, and it recovered by itself at 14:31. A thread dump taken at 14:20 shows 200 threads in SocketInputStream.read. Walk me through it."

Reveal answer

The real test Whether you recognise thread-pool exhaustion by a dependency and know why the logs were silent.

Strong answer The symptom set — low CPU, no errors, every thread blocked reading a socket — is thread-pool exhaustion caused by a downstream that stopped answering.

The evidence to collect: the thread dump's stack frames below read will name the client and usually the URL, so I identify the dependency; then I check that dependency's latency graph and the connection state on the checkout side.

The logs were silent because nothing failed — every thread was still waiting, and a request that has not finished writes no error. Recovery at 14:31 is the moment the downstream came back and the parked reads completed.

The likely causes, ranked:

  1. Read timeout: missing or very long on that client, so each call waited as long as the downstream stalled.
  2. No bulkhead, so one dependency was allowed to take all 200 threads.
  3. No circuit breaker, so calls kept being attempted into a dead service.

The fix, in order:

  1. Set a read timeout in the hundreds of milliseconds.
  2. Add a bulkhead so that dependency can hold at most a fraction of the pool.
  3. Add a breaker with a fallback.
  4. Alert on the pool's active-thread count.

Prevention is a service template where no outbound HTTP client can be created without a timeout.

Picture it The request thread pool of checkout at four moments, the thread dump that reveals the cause, and the bulkhead that would have contained it. See Pattern: Bulkhead and Pattern: Timeout.

Make the invisible visible: Busy request threads over time, with no limit on the pricing client.

pool occupancyruns offline
# illustrative output  (tomcat.threads.busy, max 200)
14:04   31 / 200   normal
14:05  120 / 200   pricing stops answering, threads park on its socket
14:08  200 / 200   pool full, new requests queue, CPU 4%, no errors logged   ✗
14:31   25 / 200   pricing recovers, parked reads complete

What you see: The dump groups into one stack that names the dependency.

thread dump excerptruns offline
# illustrative output (frame names abridged)
"http-nio-8080-exec-17" RUNNABLE
   at ...SocketInputStream.read(...)
   at ...PricingClient.getPrice(PricingClient.java:41)
   at ...CheckoutService.price(CheckoutService.java:88)
(198 more threads with the identical stack)

The fix: A short read timeout, a bulkhead that caps the dependency's share, and an alert on busy threads.

application.ymlruns offline
resilience4j:
  bulkhead:
    instances:
      pricing:
        max-concurrent-calls: 20      # ✅ FIX: pricing can hold at most 20 of 200 threads
        max-wait-duration: 0          # reject at once instead of queueing

What you see now: The same stall, with the cap in place.

pool occupancy (fixed)runs offline
# illustrative output
14:05   45 / 200   pricing stalls, 20 threads parked, others fail fast to the fallback
14:08   48 / 200   ✓ 152 threads free, checkout still serves non-pricing work

Land it A service brought down by waiting shows no errors, which is exactly why the thread dump, not the log, is the first thing I ask for.

Likely follow-ups
"You added the read timeout and the bulkhead, and it happened again the next week with threads in a different frame. What next?"

Then the first fix was right for one dependency and there is another unbounded wait.

I would take the new thread dump and read the frames below the top one, because the frame names the resource: if it is a database driver's socket read, the JDBC statement has no query timeout and the database is the stalled dependency; if it is a connection-pool acquire — HikariCP's getConnection — the database pool is exhausted, which usually means a slow query is holding connections; if it is a lock or a synchronised block, the service has a contention problem of its own.

Each has its own bound: a JDBC queryTimeout or a PostgreSQL statement_timeout, a HikariCP connectionTimeout, a lock with a timeout.

The lesson I would take is that the first incident should have prompted an inventory of every place a request thread can wait, not just the one that was caught, and I would make that inventory the next task.

How the frame below the top one names the waiting resource.

reading the framesruns offline
# illustrative output
...SocketInputStream.read + PricingClient       -> HTTP read timeout missing
...SocketInputStream.read + JDBC driver         -> JDBC query timeout missing
...HikariPool.getConnection                     -> database pool exhausted, a slow query holds connections
...BLOCKED on a synchronized method             -> lock contention inside the service
"Why did the health check not catch this, and what health check would have?"

The health check almost certainly ran on a different thread pool — the management port in Spring Boot uses its own — and returned "up" because the process was alive, the database was reachable, and nothing it tested was the request pool.

A health check that would have caught it measures the resource that failed: the number of busy request threads against the maximum, exposed by Tomcat's metrics as tomcat.threads.busy.

The readiness probe should turn unhealthy when the pool has been saturated for more than a few seconds, so the load balancer stops sending traffic to that instance and the traffic goes to instances that still have threads.

I would not make the health check call the downstream dependency, because then the checkout service reports unhealthy whenever pricing is slow, and the platform removes healthy instances for someone else's problem.

The right check is "can I take a request", not "is everyone I depend on fine".

"Would virtual threads have prevented this?"

Partly, and it is worth being precise. With virtual threads, the 200-thread limit disappears: each request gets a cheap virtual thread, so the service would have kept accepting requests instead of stalling at 200.

But every one of those requests would still have been blocked waiting on the same dead dependency, now with 20,000 of them parked, each holding a database connection, a pooled HTTP connection, or memory for its request.

The service would appear alive and would consume more memory until something else broke — the database pool, or the heap. So virtual threads move the failure from "no threads" to "no connections" or "no memory" and make it slower and less obvious.

The timeout is still the fix, and the bulkhead still matters, because its job becomes protecting the dependency and the connection pools rather than the thread count. Virtual threads remove one symptom and none of the causes.

"How would you have found the dependency in the thread dump in thirty seconds?"

I would not read 200 stacks; I would aggregate them. A tool such as the fastthread.io analyser, or a one-line script that groups the dump's stacks by their top ten frames and counts them, shows in seconds that 200 threads share one stack.

Reading down that one stack, the frames after SocketInputStream.read name the HTTP client class, then the interceptor or the generated client, and usually a method name such as PricingClient.getPrice.

If the stack does not name the target, the connection is identifiable from the operating system: ss -tnp on the pod lists established connections by remote address and port, and 200 connections to the same address is the answer.

In a service with tracing, the current spans of the blocked threads carry the URL, and the tracing UI shows a wall of open spans against one dependency. I keep those three techniques in the runbook so nobody has to think of them at 14:20.

Q14. "What is deadline propagation and why does it matter more than any single timeout?"

Reveal answer

Strong answer Deadline propagation means the first service in a call chain decides the total time the user's request may take — say 2 seconds — and every downstream call carries the remaining time, so no hop ever waits longer than the user will.

Without it, each hop has its own independent timeout. If five services each allow 1 second, the chain can take 5 seconds while the user's browser gave up at 2.

The last four seconds of work are wasted on a request nobody is waiting for.

With it, the fourth hop sees "you have 180 milliseconds left" and either finishes in time or fails immediately, freeing its thread. gRPC carries deadlines natively, and the client library computes the remaining budget on every outbound call.

Over REST you carry an absolute deadline in a header.

  • Timestamp, not a duration, so clock skew of a few milliseconds is tolerable.
  • Client timeout is the minimum of its configured value and the remaining budget.

The senior follow-up is cancellation: when the deadline passes, the work in flight should stop, which in Java means checking the deadline in long loops and using clients that support cancelling the underlying request.

Picture it A request with a 2-second budget crossing five services, shown with per-hop timeouts alone and with a propagated deadline. See Pattern: Timeout.

Make the invisible visible: The header the edge writes and each hop reads.

deadline headerruns offline
# edge service, request arrives at 1724857198150 ms, budget 2000 ms
X-Deadline: 1724857200150
# each hop: remaining = deadline - now; timeout = min(configured, remaining)

The trace: Each hop with its own 1-second timeout, then with the propagated deadline.

per-hop versus deadlineruns offline
PER-HOP ONLY (each hop allows 1000 ms)
  hop1 400 ms, hop2 900 ms, hop3 stalls for its full 1000 ms
  chain is at 2300 ms and still going; the user left at 2000 ms          ✗
DEADLINE 2000 ms
  hop1 takes 400 ms  -> hop2 sees 1600 ms left
  hop2 takes 900 ms  -> hop3 sees 700 ms left, timeout = min(1000, 700)
  hop3 stalls        -> fails at 700 ms, chain ends at 2000 ms             ✓

What you see: The log line a hop writes when it refuses to start work.

hop logruns offline
# illustrative output
WARN trace=ab12 hop=inventory remaining=12ms floor=20ms -> fail fast, not sent

Why: The deadline is the outer envelope and each per-hop timeout the inner one, and a hop applies the smaller of the two.

Land it Per-hop timeouts protect each service from its callee; a propagated deadline protects the whole chain from doing work the user has stopped waiting for.

Likely follow-ups
"Implement it over REST for me — what is the header, what does each hop do, and where does the clock come from?"

The edge service sets an absolute deadline: it takes its own timestamp at arrival, adds the total budget, and writes X-Deadline: 1724857200150 as milliseconds since the epoch.

Every service reads that header in an inbound filter and stores it in the request context, alongside the trace id.

Each outbound client interceptor computes the remaining budget as deadline minus now, and if that is below a floor such as 20 milliseconds it fails immediately without sending; otherwise it sets the per-request timeout to the smaller of the configured read timeout and the remaining budget, and forwards the same header unchanged.

The clock is the server's own, synchronised by NTP, which is typically within a few milliseconds across a data centre — good enough because I am budgeting in hundreds of milliseconds.

I carry a timestamp rather than a duration so that time spent in queues between hops is counted. The edge is the only place that decides the total, and the total is a product decision, such as 2 seconds for a page.

"What goes wrong if the clocks are skewed by a second?"

A second of skew on a two-second budget means one hop believes it has either one second more or one second less than it really does.

Too little and it fails work that would have finished in time; too much and it works a second past the point the user gave up.

Neither is catastrophic, but a one-second skew is a broken NTP setup, not a normal condition — a healthy cluster is within single-digit milliseconds.

The defences are to monitor clock offset as a platform metric and alert above, say, 50 milliseconds; to clamp the remaining budget on each hop to the hop's own configured maximum so a wildly wrong deadline cannot extend a timeout; and to treat a deadline already in the past at arrival as suspicious rather than fatal, logging it and applying the default timeout instead of rejecting everything.

In practice the clamp is what keeps a clock bug from turning into an outage.

One second of skew on a 2000 ms budget, with and without the clamp.

clock skewruns offline
# illustrative output: header deadline 1724857200150, true now 1724857198200 (1950 ms left)
hop clock 1 s ahead   remaining looks like 950 ms   -> fails good work early      ✗
hop clock 1 s behind  remaining looks like 2950 ms -> clamp to hop max, 500 ms    ✓
"How do you make cancellation actually happen in a Spring service when the deadline passes?"

Three places. For outbound HTTP, the client's per-request timeout is already the remaining budget, so the call fails when the deadline passes and the thread returns.

For database work, I set the JDBC statement's query timeout to the remaining budget before executing, which makes PostgreSQL cancel the query server-side; in Spring that is JdbcTemplate.setQueryTimeout or the timeout attribute of @Transactional, which Spring converts into a statement timeout.

For in-process loops — building a large response, iterating over a collection — I check the deadline at reasonable intervals and throw a deadline-exceeded exception. With virtual threads or reactive code, cancellation also propagates to whatever the request is awaiting.

The one thing that cannot be cancelled is a synchronous call already made to a third party with no deadline support; that is the case where the budget floor matters, so I do not start it with 20 milliseconds left.

"Does the deadline replace per-hop timeouts?"

No, they answer different questions. The per-hop timeout says "this dependency normally answers in 50 milliseconds, and if it has not answered in 300 it is broken, so stop waiting". The deadline says "the user stops caring at 2 seconds, so never work past that".

A hop must apply the smaller of the two.

If only the deadline existed, a stalled dependency early in a chain would be waited on for the full two seconds before anyone gave up, and the caller's thread pool would fill as surely as with no timeout at all.

If only per-hop timeouts existed, five hops at 500 milliseconds each would work for 2.5 seconds on a request the user abandoned at 2.

The pair together give fast failure for a broken dependency and a hard ceiling for the whole chain; the deadline is the outer envelope and the per-hop timeout is the inner one.

Q15. "A call to the payment service returned nothing — the client timed out. Did the payment happen? What does that tell you about retries?"

Reveal answer

Strong answer I do not know, and that is the whole point. A timeout is consistent with three different histories.

  • Lost request: the request never reached the payment service.
  • Lost reply: the payment service processed it and the reply was lost.
  • Still running: the payment service is still processing it.

From the caller's side they are indistinguishable — this is the fundamental limit the Distributed Systems primer describes as the two-generals problem. So a naive retry has a one-in-three chance, roughly, of charging the card a second time.

The conclusion is that retrying a non-idempotent operation after a timeout is a bug, not a resilience feature.

A retry is safe only if the receiver can recognise it as a repeat: the caller attaches an idempotency key — a unique id generated once for the logical operation, before the first attempt — and the receiver stores the key with the outcome and returns the stored outcome on a repeat.

With that in place, "did it happen?" no longer needs answering: retry until you get a definite response, and the result is the same either way.

Without it, there are two honest options on a timeout.

  • Record and reconcile: record the operation as unknown and reconcile later.
  • Query first: query the receiver by a reference id before retrying.

Picture it A timed-out payment call drawn as three possible histories, and what a retry does to the payments table with and without an idempotency key. See Pattern: Retry with backoff and the same idea on the receiving side in Pattern: Idempotent consumer.

Make the invisible visible: Three histories the caller cannot tell apart.

three historiesruns offline
Checkout            Payment                 caller sees
send charge ------> (never arrives)          timeout     1: request lost
send charge ------> charge done, reply lost  timeout     2: it happened
send charge ------> still processing         timeout     3: it may happen

The trace: The payments and idempotency_keys tables after one timeout and one retry.

table stateruns offline
WITHOUT a key   attempt 1 timeout -> retry -> attempt 2 ok
  payments: (501, 49.90, CAPTURED) (501, 49.90, CAPTURED)   ✗ charged twice
WITH key k-7f   attempt 1 timeout -> retry with k-7f
  idempotency_keys: (k-7f, COMPLETED, 201)
  payments: (501, 49.90, CAPTURED)                          ✓ charged once, same reply returned

Why: A timeout means unknown. A retry is safe only if the receiver can recognise a repeat.

Land it A timeout means "unknown", never "failed", and every retry policy has to be designed around that word.

Likely follow-ups
"Where exactly does the idempotency key get generated, and what if the client itself crashes before saving it?"

The key is generated by the client once per logical operation, before the first attempt, and — this is the part people miss — stored durably before the first attempt is sent.

In a checkout service that means inserting the key into the order row or a pending-operation row in the database, committing, and only then calling payment.

If the client crashes before that commit, no call was ever made, so nothing happened and the user simply retries from the start with a fresh key.

If it crashes after the commit but before or during the call, on restart a sweeper finds the pending operation with its key and re-sends with the same key, and the payment service returns either the stored outcome or performs the charge once.

If the key lived only in memory, the crash would lose it, the retry would use a new key, and the guarantee would be gone at exactly the moment it was needed. So the key is a durable fact about the operation, not a request header.

"The payment provider is a third party with no idempotency key. What do you do on a timeout?"

Then I cannot retry blindly and I cannot ignore it, so I reconcile. On the timeout I record the payment attempt as UNKNOWN with the provider reference I sent — most providers accept a merchant reference or order number even if they do not offer idempotency.

I then query the provider: a "get transaction by merchant reference" call, or a status endpoint, or at worst their daily settlement report.

If the provider confirms the charge, I mark it successful and proceed; if they say no such transaction, I retry with a new attempt; if they are unreachable, I wait and query again on a schedule, with the order shown as "payment pending" to the user.

What I do not do is either retry immediately, which risks a double charge, or mark it failed, which risks a customer who was charged and got nothing. Most double-charge incidents I have seen came from a timeout treated as a failure.

The unknown attempt and the reconciler's three possible findings.

payment_attemptsruns offline
# illustrative output
payment_attempts: id 91  order 501  provider_ref ord-501  status UNKNOWN  (timeout 14:02:11)
reconciler 14:03  GET /transactions?merchant_ref=ord-501
  found        -> CAPTURED, order proceeds                   ✓
  not found    -> new attempt 92 with a new reference         ✓
  unreachable  -> stays UNKNOWN, query again on schedule      ✓ never marked failed
"How does this change if the call is idempotent by nature — a GET, or a PUT that sets a value?"

Then a retry after a timeout is safe, because repeating it produces the same end state: a second GET reads the same data, a second PUT that sets status to SHIPPED leaves it SHIPPED. The client can retry those without a key, and the retry policy can be more aggressive.

The care needed is in the word "by nature": a PUT that increments, a POST that appends, or a DELETE that returns an error on the second call because the row is gone are not idempotent even if they use an idempotent-looking verb, and a PUT whose effect depends on the current state — "set price to current plus 10%" — is not idempotent either.

So I classify each operation explicitly in the client, idempotent or not, rather than trusting the HTTP method, and the retry configuration is attached to that classification. Resilience4j lets you retry on a per-call basis, so the classification becomes code.

"What does the reconciliation job look like, and how often does it run?"

It is a scheduled job that compares two ledgers and produces a list of differences.

For payments it selects every attempt in UNKNOWN older than a few minutes and queries the provider for each; for the whole system it compares, per hour, the count and sum of orders marked PAID against the count and sum of charges the provider settled.

Differences go to a queue with a human owner and an alert if the count is above a small threshold.

It runs continuously for the UNKNOWN sweep — every minute — and hourly for the aggregate comparison, with a daily full comparison against the provider's settlement file.

The job is more valuable than it looks: it is the mechanism that catches every bug in the payment path, not just timeouts, and I have seen it find a dual-write gap that the metrics had missed for a quarter.

Its output should be near zero on a normal day, so any number is a signal.

Q16 · Design. "Design the server side of idempotency keys for a payment API. Cover storage, concurrent duplicates, mismatched bodies, and expiry."

Reveal answer

Strong answer Requirements: a repeated request with the same key returns the same result without repeating the side effect, even if the repeats arrive at the same moment or a day later.

Design: a table idempotency_keys(key, request_hash, status, response_code, response_body, created_at) with the key as primary key, scoped per API client so two clients cannot collide. On a request the handler follows these steps.

  1. Insert: insert the key with status IN_PROGRESS inside the same database transaction that will perform the charge.
  2. First arrival: if the insert succeeds, I do the work, then update the row with the final response in the same transaction, so the outcome and the key commit together.
  3. Repeat: if the insert hits the primary key, I read the row: if COMPLETED, I return the stored response with the original status code; if IN_PROGRESS, a concurrent duplicate is running, and I return 409 Conflict so the client retries in a moment rather than getting two charges.

I store a hash of the request body and return 422 if a repeat arrives with a different body under the same key, because that is a client bug, not a retry.

Keys expire after 24 hours by a background delete; Stripe uses the same window.

The trade-off is one extra row write per request, which is cheap next to a payment. What I would not do is keep keys only in Redis, because losing the cache loses the guarantee at the moment it matters most.

Picture it Two identical requests racing on the idempotency table, with the rows each transaction sees at each step. See Pattern: Idempotent consumer for the same idea on a consumer.

The setup: The table, with the primary key scoped per API client.

idempotency_keys.sqlruns offline
CREATE TABLE idempotency_keys (
  client_id     text,
  key           text,
  request_hash  text,
  status        text,          -- IN_PROGRESS or COMPLETED
  response_code int,
  response_body text,
  created_at    timestamptz,
  PRIMARY KEY (client_id, key)
);

The trace: Two requests with the same key, same-transaction design.

two transactionsruns offline
t1  T1  INSERT key k-7f IN_PROGRESS       ✓ row inserted, not yet committed
t2  T2  INSERT key k-7f                   blocks, waiting for T1 to finish
t3  T1  charge, UPDATE status=COMPLETED, COMMIT   ✓
t4  T2  unique violation -> SELECT -> COMPLETED -> return stored 201   ✓
ledger  1 charge, 2 identical responses

What you see: The mismatched-body check.

mismatchruns offline
POST /payments  Idempotency-Key: k-7f   amount=49.90   -> 201
POST /payments  Idempotency-Key: k-7f   amount=59.90   -> 422 (client bug)   ✓ no second charge

Why: The key and the side effect commit together, so a crash can never leave one without the other.

Land it The key and the side effect must commit in one transaction, or the guarantee has a hole exactly where a crash would find it.

Likely follow-ups
"Two identical requests arrive within a millisecond. Walk me through what each transaction sees."

Both open a transaction and both attempt INSERT INTO idempotency_keys with the same primary key. The first insert succeeds and that transaction goes on to perform the charge.

The second insert blocks — in PostgreSQL a unique-index insert waits for the conflicting uncommitted row's transaction to finish — until the first commits or rolls back.

If the first commits, the second insert fails with a unique violation; my code catches it, reads the row, finds COMPLETED with the stored response, and returns it, so the client gets the same 201 as if it had been the first.

If the first rolls back, the second insert then succeeds and proceeds, which is right because nothing happened.

The 409 for IN_PROGRESS only applies when the second request arrives after the first's row is committed as IN_PROGRESS — which happens if the design commits the key in a separate, earlier transaction.

So the design choice matters: same transaction means blocking and no 409; separate transaction means a fast 409 and a client retry.

"Why store the response body, and what if the response is large or contains secrets?"

I store the response so the repeat returns exactly what the original returned, including the status code and the generated payment id, because the client may have never seen the first response and needs it to proceed.

If it is not stored, the repeat has to be reconstructed from the current state, which may have moved on — the payment may since have been refunded — and the client gets a different answer to the same request, which defeats the purpose.

For size, payment responses are small, a few hundred bytes; for a larger API I store a reference to the created resource plus the status code and regenerate the body.

For secrets, the stored body should not include anything the original response would not have returned to that client, and since the key is scoped per client, only that client can retrieve it.

The row is deleted after the expiry window, so the data has a bounded life.

"Why 24 hours? What is the cost of a longer window, and what does a client do after expiry?"

The window has to be longer than any plausible retry, including a client that crashed and came back after a deploy or an incident, and 24 hours comfortably covers that; retries measured in days are not retries but new operations.

A longer window costs storage — at a thousand payments a second, 24 hours is 86 million rows, which is manageable in one table with an index on created_at for the cleanup, but a month is 2.6 billion, which needs partitioning.

It also lengthens the time a client bug that reuses a key can silently return stale responses.

After expiry, a repeat with the same key is treated as a new request, so a client that retries a day later could double-charge; the defence is a business-level check — payment for an order that is already PAID is refused — which is a separate rule from the idempotency table and should exist anyway. Stripe's choice of 24 hours is a reasonable industry reference point.

The storage arithmetic behind the window.

storage arithmeticruns offline
1,000 payments/s x 86,400 s   =        86,400,000 rows per 24 h   one table, index on created_at ✓
1,000 payments/s x 30 days    =     2,592,000,000 rows            needs partitioning ✗
"How do you test this? What would the test for the concurrent case look like?"

Three tests.

  1. Repeat: send the same request twice sequentially and assert the second returns the identical status and body, and that the charge count in the ledger is one.
  2. Mismatch: send the same key with a different amount and assert 422 and no second charge.
  3. Concurrency (the one worth writing carefully): start two threads with a latch so both send the same request within the same millisecond, against a real database in a container, and assert exactly one charge and two identical responses, or one response and one 409 depending on the design.

I run the concurrency test a hundred times in a loop because races do not show up once.

For production verification I add a metric for idempotency hits per minute — a baseline of a fraction of a per cent from client retries is normal, a spike means a client is looping, and zero for a day means the header stopped being sent.

"Why not Redis for the key table, given the payment database is the hot path?"

Because the guarantee has to survive exactly the events that lose a cache.

If Redis is restarted, fails over to a replica that had not replicated the last writes, or evicts under memory pressure, the key for a charge made a second ago is gone, and the retry that arrives next charges again.

Those events cluster during incidents, which is also when clients retry most. The database row costs one insert and one update per payment in the transaction I am already running, which is negligible next to the charge itself.

Where Redis is useful is as a front: a fast check that returns the stored response for completed keys without touching the database, with the database as the authority on a miss.

That gives the speed for the common repeat and keeps the guarantee where it belongs. A single-node cache is fine for that role because a miss just falls through to the truth.

Q17. "Which failures should be retried, which never, and what does 'exponential backoff with jitter' actually mean?"

Reveal answer

Strong answer Retry only failures that a second attempt could plausibly fix.

  • A connection refused or reset.
  • A read timeout on an idempotent call.
  • A 503 Service Unavailable.
  • A 429 Too Many Requests, after the indicated wait.

There are three things to never retry.

  • A 400, 401, 403, 404, or 422, because the request itself is wrong and will be wrong again.
  • A non-idempotent call after a timeout.
  • Anything once a circuit breaker has judged the dependency down.

Exponential backoff means each retry waits longer than the last — 200 milliseconds, then 400, then 800 — so a struggling service gets increasing breathing room. Jitter means adding a random amount to each wait, for instance anywhere from 0 to 100% of the base delay.

Jitter matters because a thousand clients that failed at the same instant would otherwise retry at the same instant and arrive as a synchronised wave, knocking the service over again as it recovers.

In Resilience4j these are enable-exponential-backoff, exponential-backoff-multiplier, enable-randomized-wait, and randomized-wait-factor, with retry-exceptions and ignore-exceptions choosing what counts. I cap attempts at three; more than that is a breaker's job.

Picture it Which failures to retry, the waits the three attempts actually use, and how jitter spreads a thousand failed clients. See Pattern: Retry with backoff.

Make the invisible visible: A decision table for the failure types.

Retry decisions by failure type
FailureRetry?Reason
Connection refused or resetYesA second attempt may reach a live instance.
Read timeout on a GETYesThe call is idempotent.
503, or 429 after the indicated waitYesThe server said try again.
400, 401, 403, 404, 422NeverThe request is wrong and will be wrong again.
Timeout on a non-idempotent POST without a keyNeverOutcome is unknown.
Breaker open (CallNotPermittedException)NoThe breaker already judged the dependency down.

The trace: Backoff with base 200 ms and multiplier 2, then the same with jitter.

waitsruns offline
attempt 1 fails -> wait 200 ms  (full jitter: 0..200, average 100)
attempt 2 fails -> wait 400 ms  (full jitter: 0..400, average 200)
attempt 3 fails -> give up, breaker's problem
1000 clients, no jitter:  all retry at t=200 ms  -> one wave of 1000       ✗
1000 clients, jitter:     spread over 0..200 ms  -> about 5 per millisecond ✓

The setup: The Resilience4j properties named in the answer.

application.ymlruns offline
resilience4j:
  retry:
    instances:
      inventory:
        max-attempts: 3
        wait-duration: 200ms
        enable-exponential-backoff: true
        exponential-backoff-multiplier: 2
        enable-randomized-wait: true
        randomized-wait-factor: 0.5

Why: A retry is for failures that last milliseconds, and jitter stops your own retries from becoming the next incident.

Land it A retry is for a failure lasting milliseconds; anything longer is a breaker's problem, and jitter is what stops your retries from becoming the next incident.

Likely follow-ups
"Show me the arithmetic for full jitter — what does the third retry actually wait?"

With a base of 200 milliseconds and a multiplier of 2, the deterministic delays are 200, 400, and 800 milliseconds.

Full jitter, the AWS-recommended form, replaces each delay with a random value between zero and that number, so the third retry waits anywhere from 0 to 800 milliseconds, with an average of 400.

Resilience4j's randomized-wait-factor of 0.5 is a narrower form: the wait is the computed delay plus or minus 50%, so the third retry waits between 400 and 1,200 milliseconds.

The purpose is to spread a thousand clients that failed together across the whole window rather than have them arrive at the same instant.

The total worst-case wait matters for the caller's budget: three attempts with base 200 and multiplier 2 plus the calls themselves can approach 2 seconds, so I check that the retry policy's total fits inside the caller's deadline, and I usually find that means two retries, not three.

"What about a 500 Internal Server Error? Retry or not?"

It depends on whether the call is idempotent, and I would say that rather than give a blanket rule. A 500 means the server hit an unexpected error; it may have completed the side effect before failing, or not.

For an idempotent call — a read, a PUT that sets a value, a POST with an idempotency key — one retry is reasonable, because transient causes such as a deadlock or a briefly unavailable dependency produce 500s.

For a non-idempotent call without a key, a 500 is like a timeout: unknown, so no retry without checking.

I would also look at what the server actually returns: a well-behaved service maps its transient failures to 503 and its bugs to 500, so if I see a steady stream of 500s the answer is a bug report, not a retry.

A 502 or 504 from a proxy is usually transient and usually safe to retry once for idempotent calls.

"Where do retries go in relation to the breaker and the bulkhead?"

The order matters and Resilience4j applies it for you: from the outside in, the retry wraps the breaker, which wraps the bulkhead, which wraps the call.

That means each retry attempt goes through the breaker separately, so if the breaker opened after the first attempt, the second attempt fails immediately with CallNotPermittedException, which I configure the retry to ignore rather than retry.

Each attempt also acquires a bulkhead permit separately, so a retry does not hold a permit while it sleeps.

If the order were reversed — the breaker outside the retry — the breaker would see one failure for three attempts and open later, and a retry storm could form before it ever tripped.

In Spring Boot's Resilience4j integration the default aspect order is retry outermost, then breaker, then rate limiter, then time limiter, then bulkhead, and it is configurable with the *-aspect-order properties if a team needs to change it.

Why the retry must sit outside the breaker.

retry outside breakerruns offline
retry( breaker( bulkhead( call ) ) )
attempt 1  breaker CLOSED, call fails                        ✗ failure recorded
attempt 2  breaker OPEN -> CallNotPermittedException         retry is configured to ignore it
           no third attempt, no storm                        ✓
"How do you know your retry policy is doing more good than harm in production?"

Two metrics, both exported by Resilience4j: the retry success rate — calls that failed once and then succeeded — and the retry exhaustion rate — calls that failed on every attempt.

A healthy policy has a high success rate on the first retry and a near-zero exhaustion rate; the retries are absorbing brief blips.

A policy doing harm shows high exhaustion, which means the dependency is down for longer than the retries span and every retry is wasted load, or it shows retry volume rising in step with the dependency's error rate, which is the retry-storm signature.

I put the retry count as a share of first attempts on the dependency's dashboard; above about 10% it is a warning.

I also confirm during a fault-injection exercise that the breaker opens within a few seconds of a sustained failure and the retry count drops to zero when it does, because that is the design working as intended.

Q18 · Scenario. "The inventory service was down for 90 seconds. It came back healthy, ran for 20 seconds at 5× normal load, and fell over again. This repeated four times. Explain and fix."

Reveal answer

The real test Whether you recognise a retry storm and know that the fix is on the callers, not the victim.

Strong answer The pattern — recovery followed by a burst several times normal load and a second collapse — is a retry storm. The evidence: request rate on inventory at the moment it came back, broken down by caller, and the retry configuration of those callers.

The likely causes, ranked:

  1. No jitter: callers retrying with fixed or unjittered delays, so every queued request from the outage retries at the same instant.
  2. Layers multiplying: retries at multiple layers multiplying the burst.
  3. No breakers: callers never stopped trying during the 90 seconds and had a backlog waiting to fire.

The fix has two sides.

  • On the callers: add jitter to backoff, cap attempts at three, and add breakers so callers back off entirely while inventory is down and probe gently in the half-open state.
  • On inventory: add load shedding so it rejects requests beyond its capacity with a fast 503 instead of trying to serve five times its limit.

Prevention: a retry budget across the platform, such as "retries may add at most 10% to normal traffic", enforced in the shared client library or the service mesh, and a load test that includes a dependency outage and recovery, not only steady state.

Picture it How retries multiply across layers, the request rate that hit inventory when it came back, and the breaker state that would have held callers back. See Pattern: Retry with backoff, Pattern: Circuit breaker and Pattern: Load shedding.

Make the invisible visible: Retries at three layers multiply instead of adding.

amplificationruns offline
gateway 3 attempts x order-service 3 attempts x inventory-client 3 attempts
= 27 calls reaching inventory for one user request when it is down    ✗

The trace: Inventory request rate around the outage, per ten seconds.

request rate at inventoryruns offline
# illustrative output  (capacity about 1200 rps, normal 1000 rps)
t=-10s   1000 rps   ✓ normal
t=0..90s    0 rps   down, callers keep queueing and retrying
t=90s    5000 rps   ✗ backlog plus synchronised retries, collapse
t=110s      0 rps   down again, and the cycle repeats four times

What you see now: The same recovery after jitter, breakers and load shedding.

breaker and rateruns offline
t=0s     breaker CLOSED -> OPEN        callers stop calling inventory
t=60s    OPEN -> HALF_OPEN             3 probe calls ✓
t=62s    HALF_OPEN -> CLOSED           offered rate ramps 300, 700, 1000 rps   ✓
inventory sheds anything above 1200 rps with a fast 503

Land it The victim cannot fix a retry storm by getting stronger; the callers have to become polite.

Likely follow-ups
"You added jitter and breakers to the callers and it still fell over on recovery. What next?"

Then the burst is not retries, or not only retries, and I would look at the queue that formed during the outage. Two common sources.

First, work that was deferred rather than dropped: a message consumer that paused during the outage and, on recovery, drains 90 seconds of backlog at full speed — that is not a retry, it is legitimate load arriving all at once, and the fix is a rate limit on the consumer's catch-up or a capacity signal from inventory.

Second, cold start: inventory came back with empty caches, cold connection pools, and an unwarmed JIT, so its capacity at second one was a fraction of its steady state, and even normal load was five times what it could handle.

The fix there is on inventory: warm caches before reporting ready, pre-open the database pool, and let the readiness probe stay unready for a few seconds after start so the load balancer ramps traffic in.

Load shedding on inventory covers both cases while the root causes are fixed.

"What does load shedding look like in code, and how does inventory know it is over capacity?"

The simplest form is a concurrency limit: a semaphore sized to the number of requests the service can serve within its latency target, acquired at the start of each request with no wait; if there is no permit, the service returns 503 immediately with a Retry-After header.

That costs microseconds per rejected request instead of holding a thread. The limit comes from Little's law: if inventory serves 500 requests a second at 40 milliseconds, its steady-state concurrency is 20, so a limit of 40 or 50 gives headroom and rejects the rest.

Adaptive versions, such as Netflix's concurrency-limits library, adjust the limit from observed latency, raising it while latency is stable and cutting it when latency climbs.

The 503 is a good signal for callers: their breakers count it as a failure and open, which reduces the offered load further. Shedding is also priority-aware if needed — reject bulk or low-value calls first.

A concurrency limit in code, sized with Little's law.

concurrency limitruns offline
// Little's law: concurrency = rate x latency = 500 rps x 0.040 s = 20
private final Semaphore permits = new Semaphore(40);      // headroom over 20

Response handle(Request r) {
    if (!permits.tryAcquire()) {                           // ✅ FIX: shed at once, no queueing
        return Response.status(503).header("Retry-After", "1").build();
    }
    try { return serve(r); } finally { permits.release(); }
}
"Whose responsibility is this — the inventory team or the callers' teams?"

Both, and the split is precise. The callers own their retry behaviour: jitter, attempt caps, breakers, and a retry budget, because they are the ones generating the amplified load and nobody else can change their client code.

Inventory owns its own protection: load shedding, warm-up before ready, and enough capacity headroom for a plausible burst, because it cannot rely on every caller being polite.

The platform team owns the default: a service template and a shared client where the polite behaviour is the default, and a mesh or client-side retry budget that limits retries as a share of traffic across the whole platform.

In the postmortem I would assign three actions along those lines rather than one, because a retry storm needs both an impolite caller and a defenceless victim, and fixing only one side leaves the next incident half-prevented.

"How would you reproduce this in a test before it happens again?"

With a fault-injection run in a staging environment under realistic load.

I generate normal traffic through the real callers with a load tool, then make inventory unavailable for 90 seconds — by scaling it to zero, or by injecting failures at the mesh with an Istio fault-injection rule — and then bring it back.

The measurements are the request rate arriving at inventory in the ten seconds after recovery, expressed as a multiple of normal, and inventory's error rate during that window. The acceptance criterion is a multiple below about 1.5 and no second collapse.

I run it before and after the fixes so the difference is on a graph, and I keep it as a recurring exercise, monthly, because retry configurations drift as teams change their clients. A chaos tool such as Chaos Mesh or Litmus can schedule it. The test is cheap next to the incident it prevents.

Q19. "Explain retry amplification with numbers, and what a retry budget is."

Reveal answer

Strong answer Retry amplification is what happens when several layers of a call chain each retry independently.

If the edge retries three times, and the service it calls retries three times, and that one's callee retries three times, then one failing request at the bottom receives 3 × 3 × 3 = 27 attempts. Add a fourth layer and it is 81.

With ten thousand users hitting the edge, the bottom service receives hundreds of thousands of extra calls.

That service is the one that is already failing, so the extra load guarantees it cannot recover.

A retry budget replaces "retry N times" with "retries may consume at most X% of normal traffic".

Each client tracks the ratio of retries to first attempts over a sliding window. When the ratio exceeds, say, 10%, further retries are dropped.

Three rules keep retries safe:

  1. Budget them: Envoy and the Linkerd mesh implement retry budgets natively.
  2. Retry at one layer only: usually the layer closest to the failure, which has enough context to know the call is idempotent. Upper layers fail fast.
  3. Breaker at each layer: it turns retries off completely once failure is sustained, so amplification only exists in the first seconds of an incident.

Picture it One failing Ledger call on the order platform, multiplied by three retrying layers, then the same traffic under a 10% retry budget (pattern: retry with backoff).

Make the invisible visible: each arrow is one layer that retries up to 3 attempts on its own.

call chain with attemptsruns offline
Edge  --3x-->  Order  --3x-->  Payment  --3x-->  Ledger (failing)
 1 user        3 calls         9 calls           27 calls arrive at Ledger

10,000 requests in one second at the Edge
  -> 10,000 x 27 = 270,000 attempts on Ledger (normal load: 10,000)

The trace: a retry budget of 10% over a 10-second window, with 1,000 first attempts per window and Ledger down.

retry budget traceruns offline
# illustrative output
first attempts   retries so far   retries/first   decision
   100                 0              0.00        ✓ retry allowed
   400                40              0.10        ✓ last retry allowed
   401                40              0.10        ✗ ratio at limit: fail as-is
  1000               100              0.10        ✗ every further retry dropped
total attempts on Ledger per window: 1000 + 100 = 1,100 (not 1000 x 27)

What you see: Ledger's inbound request rate during the incident.

Ledger request rateruns offline
# illustrative output
                      without budget      with 10% budget
Ledger req/s (before)      10,000             10,000
Ledger req/s (incident)   270,000             11,000
Ledger recovers?              no              yes, load is near normal

Land it Retries are a multiplier, and the only safe multiplier in a deep chain is one that is budgeted and applied once.

Likely follow-ups
"Which layer should keep the retries, and why that one specifically?"

The layer that knows two things: whether the call is idempotent, and whether the failure is the kind a retry fixes.

That is usually the direct caller of the failing dependency — the service that owns the client code — because it can attach an idempotency key, classify the exception, and check the remaining deadline.

Layers above it should fail fast, returning an error or a fallback to their own caller, and the edge should never retry a request that has already fanned out below it.

A mesh can hold retries instead, with the important limitation that it does not know whether a POST is safe to repeat, so a mesh retry policy should be restricted to idempotent methods and connection-level failures.

Whichever layer is chosen, it is written into the service template and the platform's review checklist, because the amplification only appears when two teams each think they are the one layer that retries.

"How is a retry budget actually implemented in a client library?"

Two counters over a sliding window, typically ten seconds: first attempts and retries. Before each retry the client checks whether retries divided by first attempts exceeds the budget ratio, say 0.1; if it does, the retry is skipped and the failure is returned as-is.

The counters live per dependency, so a budget exhausted for pricing does not affect payment.

A small minimum keeps a low-traffic client from being starved of retries by the ratio alone. For example, allow at least ten retries per second regardless.

Linkerd implements exactly this with retryBudget settings of retryRatio, minRetriesPerSecond, and ttl; Envoy has a similar retry budget in its circuit breaker settings.

In Java there is no standard Resilience4j budget module, so teams either write a small predicate that Resilience4j's retry consults, or rely on the mesh. The key property is that under sustained failure, retries fall to the budget instead of tripling load.

"Give me the amplification number with breakers in place — how much does it help?"

It bounds the amplification in time rather than in multiple. In the first seconds of the outage, before any breaker has enough samples, the 27-times amplification is real.

Take a breaker with a window of 20 calls and a 50% threshold, on a path doing 50 calls a second. At the bottom layer it opens within about half a second.

Its failures then propagate upward as fast errors. The layers above see failures and open within another second or two.

After that, the bottom service receives only half-open probes: a few calls every 10 to 30 seconds per caller instance. For a hundred instances that is a few calls a second rather than tens of thousands.

So the bill is a couple of seconds of 27-times load, then near zero. That is why breakers and budgets are complementary: the budget caps the multiple during those first seconds, and the breaker removes the load afterwards.

Ledger load over the incidentruns offline
# illustrative output
t=0s    outage starts, no breaker has samples      27x load on Ledger
t=0.5s  bottom breaker opens (20 calls, 50%)       Payment fails fast
t=2s    upper breakers open                        Ledger sees probes only
t=2s+   half-open probes, ~100 instances           a few calls/s, near zero

Q20. "Walk me through the three states of a circuit breaker and exactly what it measures to move between them."

Reveal answer

Strong answer A circuit breaker wraps a call and keeps a sliding window of recent outcomes. It moves between three states:

  1. Closed: calls pass through and each outcome is recorded as a failure, a success, or a slow success (a call that succeeded but took longer than the configured slow-call threshold).
  2. Open: once the window holds at least a minimum number of calls (Resilience4j's minimum-number-of-calls, say 10), the breaker computes the failure rate and the slow-call rate. If either crosses its threshold (say 50%), it opens. Every call then fails immediately with CallNotPermittedException, without touching the network, and the caller's fallback runs. That frees the caller's threads and stops load on the dependency.
  3. Half-open: after wait-duration-in-open-state, say 10 seconds, the breaker lets a small number of trial calls through, for example 3. If they succeed at an acceptable rate it closes. If they fail it reopens and waits again.

The window can be count-based (the last 20 calls) or time-based (the last 60 seconds). Count-based reacts faster on low-traffic paths.

The exceptions that count as failures are configurable.

A 4xx from the callee should be ignored, because a bad request is not a sign the dependency is down.

Picture it The breaker on Order's call to Payment, stepped through CLOSED, OPEN and HALF_OPEN with the counts it uses (pattern: circuit breaker).

Make the invisible visible: the state machine with its transition rules.

state machineruns offline
              failure or slow rate >= 50%
              (and window has >= 10 calls)
  CLOSED ------------------------------------> OPEN
     ^                                            |
     |  trial calls ok                            | wait 10 s
     |                                            v
     +---------------------------------------- HALF_OPEN
                trial calls fail -> back to OPEN, wait 10 s again

The trace: window of 20 calls, minimum 10, threshold 50%.

breaker traceruns offline
# illustrative output
t=0s   CLOSED     window 20: 19 ok,  1 fail   5%   ✓ call passes
t=4s   CLOSED     window 20: 12 ok,  8 fail  40%   ✓ still under 50%
t=6s   CLOSED     window 20:  9 ok, 11 fail  55%   ✗ threshold crossed -> OPEN
t=7s   OPEN       call -> CallNotPermittedException, 0 network calls, fallback runs
t=16s  HALF_OPEN  3 trial calls: ok, ok, ok        ✓ -> CLOSED

What you see: the transition in the logs and the rejected call.

consoleruns offline
# illustrative output
INFO  CircuitBreaker 'payment' changed state from CLOSED to OPEN
WARN  OrderService  fallback used: payment unavailable, order saved as PENDING_PAYMENT
INFO  CircuitBreaker 'payment' changed state from OPEN to HALF_OPEN
INFO  CircuitBreaker 'payment' changed state from HALF_OPEN to CLOSED

Land it A breaker's job is to stop calling a dependency that is down and to fail fast so the caller stays healthy; protecting the caller from errors is a side effect, not the purpose.

Likely follow-ups
"Is the breaker per instance or shared across instances? What difference does it make?"

In Resilience4j and most libraries it is per instance — each pod has its own window and its own state.

The consequence is that each instance has to learn the dependency is down on its own.

A hundred instances make a hundred times the minimum-calls worth of failing attempts before all are open, and each probes separately in half-open.

That is usually acceptable and it has a benefit: a dependency problem visible to one instance — a bad network path from one node — does not open the breaker on all of them.

A shared breaker, with state in Redis or a mesh control plane, reacts once for all instances and probes once. It adds a dependency and a coordination cost to every call.

A mesh sidecar sits in between: it is per pod.

Its outlier detection ejects a specific unhealthy upstream instance from the pool rather than declaring the whole dependency down.

For most services I keep it per instance and size minimum-calls low enough that each instance opens fast.

"What should the fallback do, and what should it never do?"

A fallback should return something cheaper, safer, or degraded: a cached value, a default that the business has approved, an empty list for a recommendations widget, or a clear "temporarily unavailable" state the caller can render.

It should be fast and it should not itself call the failing dependency. It should never make a business decision that the dependency was there to make — approving a fraud check because fraud is down, or treating "could not verify stock" as "in stock".

It should never retry the same call, because then the breaker is bypassed.

And it should never fail silently: every fallback execution is counted in a metric, so a breaker that has been open for an hour is visible even though every request succeeded from the caller's point of view.

My rule is that the fallback is a product decision written in code, and I have the product owner sign off on what the user sees.

"The dependency returns 200 with an error inside the body. Does the breaker see that?"

Not unless I tell it to. A breaker counts exceptions and, if configured, slow calls; a 200 response with {"status":"error"} in the body is a success as far as the HTTP client is concerned.

So I map it, in one of two ways:

  • Exception: the client throws a specific exception when the body indicates failure.
  • Predicate: Resilience4j's recordResult predicate lets the breaker inspect the returned object and count it as a failure.
what the breaker recordsruns offline
HTTP 200 {"status":"error"}   no mapping    -> recorded as success  ✗ breaker never opens
HTTP 200 {"status":"error"}   recordResult  -> recorded as failure  ✓
HTTP 404 customer not found   ignore-exceptions -> not recorded     ✓ dependency is fine

The two classifications go in opposite directions, and both matter.

The reverse is also important: a 404 for "customer not found" is an exception in many clients but is not a sign the dependency is down, so I put those exception types in ignore-exceptions.

Getting this classification wrong in either direction produces one of two bad breakers. One never opens against a failing dependency. The other opens because of legitimate not-found responses.

I review the classification with the dependency's team, because they know which of their responses mean "I am broken".

"How do you verify the breaker works in production rather than trusting the config?"

Two ways.

Continuously, I export the breaker's state and its recorded rates — Resilience4j publishes resilience4j.circuitbreaker.state, calls, and failure.rate to Micrometer — and I alert on a breaker that has been open for more than a couple of minutes, and on a breaker that has never recorded a call, which means it is not wired to the code path.

Actively, I inject a fault: in staging, block the dependency and watch the state metric go closed, open, half-open, closed with the timing I expected; in production, a canary exercise where one instance's breaker is forced open through the actuator endpoint verifies the fallback path really works with live traffic.

The most common finding from these checks is a breaker that is configured in the properties file but not applied.

The annotation was on a method called from within the same class, which Spring's proxy does not intercept.

self-invocation bypasses the proxyruns offline
@Service
class OrderService {
    public void place(Order o) { callPayment(o); }   // ❌ TRAP: same-class call, no proxy

    @CircuitBreaker(name = "payment", fallbackMethod = "pending")
    void callPayment(Order o) { /* HTTP call */ }    // breaker never runs
}
// ✅ FIX: move callPayment into a separate bean and inject it
// Result: metric resilience4j.circuitbreaker.calls stays empty for 'payment'
Drill · Breakers, bulkheads, gateways and the mesh

This group tests the sizing arithmetic behind resilience settings and whether you can place discovery, gateway, and mesh responsibilities correctly.

Q21. "How do you choose the sliding window size, minimum calls, and thresholds for a breaker? Give me numbers for a call that happens 50 times a second."

Reveal answer

Strong answer I size the window so it reacts within the time I am willing to keep hurting the dependency, and I size the minimum-calls floor so a handful of failures on a quiet path cannot open it by accident.

The numbers at 50 calls a second:

  • Window: a count-based window of 100 represents the last two seconds, which is a good reaction time.
  • Minimum calls: 20, so the breaker never judges on fewer than 20 outcomes.
  • Failure rate: 50% is the usual starting point. For a dependency whose fallback is cheap and safe I would lower it to 30%, because being wrong about a healthy service costs little.
  • Slow-call threshold: the one people forget. Set slow-call-duration-threshold just above the dependency's healthy p99. If it answers in 60 milliseconds at p99, use 200.
  • Slow-call rate: 50%, so a dependency that is technically succeeding but stalling still trips the breaker before it exhausts threads.
  • Recovery: wait-in-open of 10 to 30 seconds and 3 to 5 half-open calls give the dependency a chance to recover without being probed hard.

Then I test the settings with a fault injection: kill the dependency in staging and watch the breaker's state metric flip at the time I expected.

Picture it Order's call to Payment at 50 calls a second, showing how the window, the slow-call line and the read timeout line up against Payment's real latency (pattern: circuit breaker, with its timeout).

Make the invisible visible: the latency axis with the three lines that matter.

latency axisruns offline
latency (ms)  0        60        200               500
              |--------|---------|-----------------|------>
              healthy   healthy    slow-call          read
              p50..p99  p99        threshold          timeout
                        (60)       (200)              (500)
call at  30 ms -> success
call at 250 ms -> slow success (counts toward slow-call rate)
call at 600 ms -> timeout     (counts as failure)

The trace: Payment degrades to 250 ms at t=0. Nothing fails, so the failure rate stays at 0%.

breaker trace at 50 calls/sruns offline
# illustrative output
t=0.4s  window  20 calls   slow 20/20 = 100%   minimum 20 reached, rate >= 50%: ✗ would open
t=1.0s  window  50 calls   slow 50/50 = 100%
t=2.0s  window 100 calls   slow 100/100        window full (2 s of traffic)
in flight at 250 ms (Little): 50 x 0.25 = 12.5 threads, vs 50 x 0.03 = 1.5 healthy

What you see: with and without the slow-call rule.

consoleruns offline
# illustrative output
slow-call rule OFF:  state=CLOSED   failure.rate=0.0   threads waiting on Payment: 12 and rising
slow-call rule ON:   state=OPEN at t~0.4s   slow.call.rate=100.0   fallback runs, threads freed

Land it The numbers come from the dependency's real latency and call rate, and the slow-call threshold matters more than the failure rate because stalls are the common case.

Likely follow-ups
"Same dependency, but the call happens twice a minute. What changes?"

Almost everything.

A count-based window of 100 would take fifty minutes to fill, and a minimum of 20 calls would take ten minutes to reach. The breaker would never react in time to matter.

For a slow path I change three settings:

  • Window: a small count-based window of 10 calls with a minimum of 5, so it judges on the last few minutes of evidence.
  • Threshold: 60% or higher, because on so few samples one or two unlucky calls are a large share.
  • Wait-in-open: a minute or more, since probing every 10 seconds on a path used twice a minute means the breaker is mostly in half-open.
window fill timeruns offline
rate 50 calls/s :  window 100 fills in   2 s        minimum 20 reached in 0.4 s
rate  2 calls/min: window 100 fills in  50 min      minimum 20 reached in 10 min
rate  2 calls/min: window  10 fills in   5 min      minimum  5 reached in 2.5 min

And I ask whether a breaker is the right tool at all: on a rare call, a timeout plus a fallback protects the caller nearly as well, and the breaker mostly adds a way to be wrong.

The window must match the call rate, or the breaker is decoration.

"Count-based or time-based window — when does each go wrong?"

A count-based window always contains a fixed number of outcomes. On a busy path it represents a short time and on a quiet path a long one.

It goes wrong on a quiet path: it can hold outcomes from an hour ago and open the breaker on a failure that ended long since.

A time-based window always covers a fixed period, such as the last 60 seconds. On a busy path it holds thousands of samples and reacts smoothly. It goes wrong in two ways:

  • Quiet path: the window may contain only two calls, which is why minimum-calls exists.
  • Bursty path: a burst of failures at the start of the window keeps the rate high for the full 60 seconds after the dependency has recovered.

For steady, high-rate paths I use time-based with a short window of 10 to 20 seconds. For anything under about 10 calls a second I use count-based.

where each window goes wrongruns offline
# illustrative output
count-based(20), 1 call/min, outage ended 1 h ago:
  window still holds 11 old failures of 20 -> rate 55% -> state OPEN   ✗ stale evidence
time-based(60 s), burst of 30 failures at t=0, dependency healthy from t=5:
  t=5s..60s  rate still ~90% -> state OPEN for ~55 s of healthy dependency   ✗
"What is the interaction between the read timeout and the slow-call threshold — which fires first?"

The slow-call threshold must be below the read timeout, and both must be above the dependency's healthy p99.

Take a read timeout of 500 milliseconds and a slow-call threshold of 200.

  • A call that stalls fails at 500 as a timeout exception, which counts as a failure.
  • A call that completes at 300 counts as a slow success.
  • Both push the breaker toward open, which is right.

If the slow-call threshold were above the read timeout, say 800, no call could ever be slow, because the timeout would fail it first. The slow-call rule would be dead configuration.

The sequence I use for a dependency with a 60-millisecond p99 is: slow-call threshold 200, read timeout 500, and a breaker slow-call rate of 50%.

That means a dependency that degrades to 250 milliseconds trips the breaker on slow rate before it stalls, which is the case that exhausts threads.

"How would you see, on a dashboard, that the settings are wrong?"

Three patterns. A breaker that flaps — its state metric alternates open and closed on a regular cycle — means the thresholds sit on top of the dependency's normal behaviour, usually the slow-call threshold near its p99.

A breaker that never opens during an incident that clearly involved the dependency means one of three things. Imagine the dependency's error rate was 80% and the caller's threads were exhausted. Then the window is too large, minimum-calls is too high, or the failures are not classified as failures.

A breaker that opens on a quiet path once a day means the count-based window holds stale outcomes.

I put these on each dependency's dashboard, all on one time axis, so the mismatches are visible at a glance:

  • the breaker state;
  • the recorded failure rate and slow-call rate;
  • the dependency's own latency p99;
  • the caller's thread-pool usage.

The dependency's latency line with the slow-call threshold as a horizontal line is the single most useful overlay.

flapping on the dashboardruns offline
# illustrative output
time        p99 latency   slow-call line   breaker state
12:00:00       190 ms        200 ms          CLOSED
12:00:30       215 ms        200 ms          OPEN      (p99 crosses the line)
12:00:45       195 ms        200 ms          CLOSED    (half-open trial under the line)
12:01:15       220 ms        200 ms          OPEN      -> flaps: the threshold sits on the p99

Q22 · Scenario. "A breaker on the fraud-scoring call flips between open and closed every fifteen seconds all afternoon. Fraud's own dashboard says its error rate is 2%. What is going on?"

Reveal answer

Strong answer The symptom is a flapping breaker: it opens, waits, half-opens, closes, and opens again in a steady cycle.

The evidence to collect: the breaker's recorded failure and slow-call rates versus fraud's error rate, and the latency of fraud calls as seen from the caller.

The cause is almost never the 2% errors. It is the slow-call rule or a mismatch of thresholds. Likely causes, ranked:

  1. Latency near the slow-call threshold: fraud's latency sits near the caller's slow-call threshold, so a large share of calls count as "slow" even though they succeed, and the breaker opens on slow-call rate.
  2. Read timeout too short: the caller's read timeout is shorter than fraud's normal p99, so timeouts are recorded as failures that fraud never sees.
  3. Tiny half-open trial count: with 1 or 2 trial calls, a single slow trial reopens the breaker.

The fix is to align the numbers with reality:

  • raise the slow-call threshold above fraud's healthy p99;
  • set the read timeout above it as well;
  • use enough half-open calls that one unlucky sample does not decide.

Then decide whether fraud's latency itself needs fixing — a flapping breaker is often the first honest signal that a dependency has quietly become slower than its consumers assume.

Picture it Order's breaker on the Fraud call, over one minute of the afternoon, with Fraud's own dashboard beside it (pattern: circuit breaker).

Make the invisible visible: the two sides count different things.

two views of the same callsruns offline
# illustrative output
                       Fraud's dashboard      Order's breaker
requests counted       only those it answered every attempt
errors                 2% (HTTP 5xx)         timeouts + connection failures + slow calls
slow-call threshold    n/a                   150 ms
Fraud latency p50      160 ms                160 ms  -> over half the calls are "slow"

The trace: one 15-second cycle, slow-call threshold 150 ms, window of 20, wait-in-open 10 s, 2 half-open trial calls.

breaker cycleruns offline
t=0s   CLOSED     window 20: slow  8/20 = 40%
t=3s   CLOSED     window 20: slow 11/20 = 55%        ✗ -> OPEN
t=3-13 OPEN       all calls fail fast, fallback runs
t=13s  HALF_OPEN  trial 1: 120 ms ok   trial 2: 170 ms slow  -> 50% ✗ -> OPEN again
t=23s  HALF_OPEN  trial 1: 110 ms ok   trial 2: 130 ms ok    ✓ -> CLOSED, cycle restarts

The fix: thresholds placed above Fraud's real p99, and more trial calls.

settings before and afterruns offline
                              before     after
slow-call-duration-threshold  150 ms     400 ms     # above Fraud's p99 (about 300 ms)
read timeout                  250 ms     800 ms
half-open permitted calls     2          5

What you see now: the same log lines after the change.

consoleruns offline
# illustrative output
slow.call.rate=8.0   failure.rate=3.0   state=CLOSED   (steady for the whole afternoon)

Land it A breaker measures the call as the caller experiences it, so the caller's timeout and slow-call settings must be tuned together or they will disagree with the dependency's own view.

Likely follow-ups
"You raised the slow-call threshold and the read timeout, and it still flaps. What now?"

Then I would stop guessing and look at the breaker's own recorded numbers rather than fraud's dashboard. Resilience4j exposes the failure rate and the slow-call rate it computed at the moment it opened, and the exception types it counted.

If the failures are real exceptions, I look at which one:

  • Connection-pool acquire timeout: the caller's pool is too small for fraud's latency. That is a problem on my side that fraud cannot see.
  • A specific 4xx counted as failure: the exception classification is wrong.

If the numbers are slow-call rate with nothing else, and fraud's latency is fine at their side, the slowness is between us.

The usual suspects are a proxy, a mesh sidecar, DNS resolution on each call, and TLS handshakes because keep-alive is off.

A trace of one slow call, with spans at the client and at fraud, shows where the time goes. Flapping that survives threshold changes is usually a caller-side or network-side cause.

"Why is 2% on fraud's side not showing as 2% on your side?"

Because the two sides count different things. Fraud counts requests it processed and answered with an error; it does not count requests it never received, requests it answered after the caller had given up, or requests that failed at a proxy in front of it.

The caller counts every attempt that did not produce a usable response in time, which includes timeouts, connection failures, and the mesh's own rejections, none of which appear in fraud's logs.

A 2% server-side error rate can coexist with a 40% caller-side failure rate when fraud's p99 sits above the caller's timeout.

same minute, two countsruns offline
# illustrative output
100 calls from Order in one minute:
  58 answered 200 within 250 ms        both sides count success
   2 answered 500                      both sides count error     -> Fraud says 2%
  40 answered after 250 ms             Order: timeout (failure); Fraud: success, late
Order sees 42 failures (42%); Fraud sees 2 errors in 60 answered (3%)

The general lesson is that a dependency's health is measured at the caller.

The mesh is valuable here. Its metrics are request rate, error rate and latency per source-destination pair, measured at the sidecar. They are the same for both teams and end the argument.

"The flapping breaker is causing fallbacks that approve orders without a fraud check. Is that acceptable?"

No, and this is where the breaker settings become a business problem. A fallback for a fraud check has to fail safe in the direction the business chooses, and "approve without checking" is the wrong direction for anything above a small amount.

The options are: fail closed, so orders are rejected while the breaker is open, which loses sales; degrade to a simpler local rule — a velocity check and a block list — which catches the obvious cases; or defer the decision, so the order is accepted as pending review and the fraud check runs asynchronously before shipment, which is often the best answer because it keeps the sale and keeps the check.

While the flapping is unresolved, I would switch the fallback to the deferred path immediately, because every open period is currently a window in which fraud is not checked, and I would report how many orders went through it so they can be reviewed.

"How many half-open calls should there be, and what does a single trial call decide?"

Enough that one unlucky sample does not decide, and few enough that a still-broken dependency is not hammered.

With one permitted call, a single slow response reopens the breaker and a single fast one closes it.

The breaker's state becomes a coin flip on the dependency's latency distribution, which is exactly the flapping in this scenario.

With five permitted calls and the same 50% thresholds, three of five must fail to reopen, which is a real signal. Ten is a reasonable ceiling for a busy path.

Resilience4j's setting is permitted-number-of-calls-in-half-open-state, and there is also max-wait-duration-in-half-open-state, which moves the breaker back to open if the trial calls do not complete within the period — worth setting, because a dependency that accepts the trial calls and then stalls otherwise leaves the breaker in half-open indefinitely.

Q23. "Semaphore bulkhead versus thread-pool bulkhead — what is the difference, and how do you size one?"

Reveal answer

Strong answer A bulkhead caps how many calls to a dependency may be in flight at once, so one slow dependency cannot consume every thread.

There are two kinds:

  • Semaphore bulkhead: a counter. The calling thread acquires a permit, makes the call on its own thread, and releases the permit. The cost is nothing but the counter, and the timeout for waiting on a permit is separate from the call's timeout.
  • Thread-pool bulkhead: hands the call to a dedicated pool with a bounded queue, so the calling thread is freed and the dependency has its own threads entirely. It isolates harder, but it costs a thread hand-off. The calling thread's context (the trace id, the security context) has to be propagated explicitly.

In Spring services with a servlet thread pool I use semaphore bulkheads. The thread-pool version fits reactive or asynchronous callers.

There are two ways to size it:

  1. A share of the pool: if the service has 200 request threads and I am willing for the recommendations dependency to consume at most 10% of them, the bulkhead is 20.
  2. Little's law: concurrency equals arrival rate times latency. A dependency called 30 times a second with a 100-millisecond latency needs about 3 permits in health. I might allow 15 to cover a slowdown before the bulkhead bites.

With virtual threads (Java 21+), the thread cost drops but the bulkhead still matters, because it now protects the dependency and the database pool rather than your own thread count.

Picture it Order's 200 request threads while Recommendations stalls, at three moments, with and without a semaphore bulkhead of 20 (pattern: bulkhead).

The setup: the call that needs the limit.

Recommendations call with a bulkheadruns offline
@Bulkhead(name = "recommendations", type = Bulkhead.Type.SEMAPHORE,
          fallbackMethod = "noRecommendations")   // ✅ FIX: at most 20 calls in flight
public List<Item> recommendations(String customerId) {
    return recoClient.fetch(customerId);          // ❌ TRAP without it: each stuck call holds a request thread
}
List<Item> noRecommendations(String customerId, BulkheadFullException e) {
    return List.of();                             // widget simply empty
}

Make the invisible visible: thread occupancy, 100 requests a second, each page needs one Recommendations call.

thread pool occupancyruns offline
# illustrative output
                      healthy 100 ms     slow 500 ms      stalled 2 s
Little: in flight         10                 50              200
NO bulkhead   threads  10/200 busy       50/200 busy      200/200 busy  ✗ checkout stuck too
bulkhead = 20 threads  10/200 busy       20/200 busy      20/200 busy   ✓ 180 free for checkout
                                         30 req/s get BulkheadFullException -> fallback

What you see: the exception on the rejected calls, and Order's other endpoints.

consoleruns offline
# illustrative output
without: GET /checkout  -> waits 12 s, then 503 (no free request thread)
with:    GET /checkout  -> 85 ms, 200
with:    WARN BulkheadFullException: Bulkhead 'recommendations' is full and does not permit further calls
         -> widget empty, page still renders

Land it The bulkhead number is a policy statement — "this dependency may have at most this much of us" — and I derive it from the pool size and the dependency's importance.

Likely follow-ups
"What happens to a request when the bulkhead is full — does it wait or fail?"

That is a setting, and I choose it per dependency. Resilience4j's semaphore bulkhead has max-wait-duration:

  • Zero: a call that finds no permit fails immediately with BulkheadFullException and the fallback runs.
  • Positive: the thread waits up to that long for a permit.

I set it to zero or a few tens of milliseconds. The point of the bulkhead is to stop threads waiting, and a long permit wait recreates the queue in a different place.

A bulkhead-full failure should be counted separately from dependency failures in the metrics, because it means "we are limiting ourselves", not "they are down", and it should not count toward the circuit breaker's failure rate.

The thread-pool bulkhead has a bounded queue instead — queue-capacity — and rejects when the queue is full; the queue is the waiting, so I keep it small, on the order of the pool size.

"Walk me through Little's law for the sizing with concrete numbers, including the slowdown case."

Little's law says the average number of calls in flight equals the arrival rate times the average time each takes.

If recommendations is called 30 times a second and takes 100 milliseconds, there are on average three calls in flight, so three permits would just cover healthy operation with no headroom.

If the dependency slows to 500 milliseconds, the same 30 calls a second means 15 in flight. If it stalls to my 2-second timeout, 60.

Little arithmeticruns offline
in flight = 30 calls/s x latency
 100 ms -> 30 x 0.1 =  3     healthy, no headroom
 500 ms -> 30 x 0.5 = 15     5x slowdown
2000 ms -> 30 x 2.0 = 60     stall at the 2 s timeout
permits = 15 -> absorbs the 5x slowdown, sheds beyond it
permits = 60 -> a stall takes 60 of 200 threads (30%)

So the bulkhead size is a choice about how much slowdown I absorb before I start shedding.

Fifteen permits absorbs a five-times slowdown and sheds beyond it. Sixty would let a stall take 60 of my 200 threads, which is the 30% I might allow for a critical dependency but far too much for a recommendations widget.

I pick the number by deciding the worst slowdown I will tolerate for that dependency's importance. I check it against the thread-pool share as a second bound, taking the smaller.

"Does the bulkhead protect the dependency, or only you?"

Both, and the second is underrated.

A bulkhead of 15 permits per instance across 20 instances means the dependency can never receive more than 300 concurrent calls from my service. That holds whatever happens on my side: a traffic spike, a retry burst, or a slow dependency of my own that makes my requests pile up.

That is a form of politeness the dependency's team can rely on and size for. In the retry-storm scenario it is one of the mechanisms that limits the burst on recovery.

The same reasoning applies to the database pool. With virtual threads and no bulkhead, ten thousand concurrent requests would all try to take a database connection, and the pool of 20 would queue them.

A bulkhead in front of the database-heavy operations keeps the queue on the request side, where it can be shed. Otherwise the queue sits in the pool, where it holds resources.

So the bulkhead is a statement about my share of them as much as their share of me.

"With the thread-pool bulkhead, how does the trace id get to the dependency call?"

It does not, unless something copies it.

The trace id, the security principal, and anything else in a thread-local live on the request thread. The call now runs on a pool thread that has none of it.

log lines across the hand-offruns offline
# illustrative output
[http-nio-8080-exec-7] traceId=4bf92f35 INFO  OrderController  GET /orders/123
[reco-bulkhead-1]      traceId=        INFO  RecoClient       GET reco-service/items   ✗ no trace header
reco-service span: parent=none  -> orphaned, the trace has a gap

The outbound request has no trace header, so the dependency's span is orphaned.

The fix is a context-propagating executor. Micrometer's ContextPropagation and its ContextExecutorService wrap the pool. Each submitted task captures the thread-locals at submission and restores them on the worker.

Spring Boot's tracing auto-configuration does this for its own executors but not for a pool you create by hand.

Resilience4j's thread-pool bulkhead has a ContextPropagator hook for the same purpose.

I test it with a single assertion: the dependency's span appears as a child of the request's span in the tracing UI. That missing propagation is the most common reason a distributed trace has gaps, and it is one of the reasons I prefer the semaphore bulkhead for servlet services.

Q24 · Design. "Design the fallback behaviour for the pricing dependency on the product page. There are three sensible options; which do you pick and when?"

Reveal answer

Strong answer Requirements: the product page must stay up when pricing is down, but a wrong price is worse than no price for a commerce business. The three options are: serve a cached last-known price, serve a default or "price unavailable" state, or fail the page.

My design layers them:

  1. Cache: a local cache in the product-page service, keyed by product id, with a time-to-live of a few minutes and refreshed on every successful call. When the breaker is open, the fallback serves the cached value if it exists and is younger than a staleness limit, say 30 minutes. It marks the price as indicative so the checkout step will re-price.
  2. No price: if there is no cached price, the fallback renders the product with a "check price at checkout" call-to-action rather than a made-up number.
  3. Checkout never falls back: it calls pricing synchronously with a tighter retry and fails the request if pricing is truly down, because charging the wrong amount is unacceptable.

The trade-off is complexity, with three code paths, against the alternative of taking the whole catalogue offline whenever pricing hiccups.

What I would not do is a fixed default price or a silent zero. Both have shipped real orders at the wrong amount in real companies.

Picture it What the product page and checkout do for the same product while Pricing is down and its breaker is open (pattern: circuit breaker, whose fallback is this decision).

Make the invisible visible: three screens, three outcomes, one dependency.

fallback per screenruns offline
Pricing breaker: OPEN

Product page  -> cache hit,  age 4 min  (< 30 min)   show 19.99, flagged "indicative"   ✓
Product page  -> cache miss                          show "check price at checkout"      ✓
Checkout      -> call Pricing sync, retry x1         still down -> reject order, no charge ✓
Checkout      -> would use cached 19.99              charge a wrong amount                ✗ never

What you see: the product-page response in each case, and the cost of the wrong design.

responsesruns offline
# illustrative output
GET /products/p-42        -> {"price":"19.99","priceStatus":"indicative","ageSeconds":240}
GET /products/p-77        -> {"price":null,"priceStatus":"checkout"}      (no cached price)
POST /checkout            -> 503 {"error":"pricing_unavailable"}           (nothing charged)
# the rejected design: default price 0.00 -> order placed at 0.00 -> shipped   ✗

Land it The fallback is a business decision dressed as code, so I choose it per screen: stale is fine for browsing and unacceptable for charging.

Likely follow-ups
"The business now says even a 30-minute-old price is unacceptable — prices change every minute in a flash sale. What changes?"

Then the staleness limit becomes a business parameter rather than a constant, and during a flash sale it drops to a minute or less. Two changes follow.

First, the cache is fed by push rather than by pull.

Pricing publishes price-change events, and the product-page service updates its local cache from them. The cache is fresh to within the event delay even when nobody has requested that product. The time-to-live becomes a safety net rather than the mechanism.

Second, when the breaker is open and the cached price is older than the limit, the page falls through to "check price at checkout" more often. The product team has to accept that a pricing outage during a flash sale shows fewer prices.

staleness limit by moderuns offline
# illustrative output
mode     staleness limit   cached price age 3 min     cached price age 40 s
normal       30 min        indicative price shown     indicative price shown
sale          1 min        "check price at checkout"  indicative price shown

The rule at checkout is unchanged: it never charges a cached price.

I would also add a flag the business can flip to set the sale mode. A one-minute limit during a normal week makes the page fall back needlessly.

"Under time pressure, which of the three layers do you build first and which do you drop?"

I would build in this order:

  1. "Check price at checkout" fallback: a few lines, it keeps the page up, and it never shows a wrong number.
  2. Checkout's synchronous re-price with fail-closed: the safety rule, and also small.
  3. The cache layer, deferred: it is the one with the most design in it.

The cache needs a time-to-live, staleness marking, refresh on success and invalidation. A first version that gets it wrong shows stale prices, which is the risk I most want to avoid.

So the first release degrades to "price unavailable, see checkout" when pricing is down, which is a visible but honest state, and the cache follows once there is time to test it.

What I would not drop is the breaker on the product page's pricing call, because without it a slow pricing service takes the product page down with it before any fallback runs.

"How do you make sure the 'indicative' price the page showed and the price at checkout do not surprise the customer?"

By treating a difference as a product event, not a silent correction. The page marks the price as indicative in the response, so the front end can render it with a small note when the flag is set.

At checkout, the service re-prices and compares with the price the cart was built with, which the front end sends along.

If they differ, checkout returns a specific response, "price changed from X to Y". The front end shows it and asks the customer to confirm before charging.

checkout re-priceruns offline
# illustrative output
POST /checkout  cartPrice=19.99
  Pricing says 21.49           ✗ differs
  -> 409 {"error":"price_changed","from":"19.99","to":"21.49"}   customer confirms, then charge
  Pricing says 19.99           ✓ -> charge 19.99

That is the same pattern used for stock changes at checkout.

A metric counts how often it happens and by how much. During normal operation it should be near zero. During a pricing outage it tells the business what the fallback cost.

Without the comparison step, the customer sees one price on the page and a different one on the receipt, which is the complaint the whole design is trying to avoid.

"Why not just have pricing push a full price list to every consumer and skip the synchronous call entirely?"

For the product page, that is close to what the push-fed cache becomes. For a catalogue of a few hundred thousand products it fits in memory.

The reasons I keep a synchronous authority for checkout are correctness and personalisation.

Prices at checkout can depend on the customer, the cart composition, the coupon, and the moment — a promotion that ends at midnight — so the "price" is the output of a computation over runtime inputs, not a value in a list.

A full list can carry base prices; it cannot carry every combination. And the business needs one place that is the truth when a dispute arises, which a pushed list on twenty consumers is not.

So the hybrid is: base prices pushed to browsing surfaces for speed and resilience, and the pricing service called synchronously at the moment money moves, with the fail-closed rule there.

Q25. "How does service discovery work in a Kubernetes platform, and why do you see fewer Eureka deployments than in 2018?"

Reveal answer

Strong answer Service discovery answers "where are the healthy instances of payment right now?" when instances are created and destroyed constantly.

Eureka, from the Netflix stack, is client-side discovery:

  1. Each instance registers itself with a registry.
  2. Each client fetches the registry.
  3. Each client load-balances across instances in its own code.

In Kubernetes the platform does this itself.

  • A Service object gives a stable DNS name and a virtual IP.
  • Kube-proxy or the CNI routes connections to the pods whose readiness checks pass.
  • The endpoints list is updated as pods come and go.

So the client just calls http://payment-service and the platform handles the rest, with no registry to run and no client library to keep in sync across languages.

Eureka still appears where teams run outside Kubernetes or need client-side load-balancing decisions the platform does not make, such as zone affinity.

The trade-off of platform discovery is coarser control. It balances connections, not requests, so a long-lived HTTP/2 or gRPC connection can pin a client to one pod.

The fix is a service mesh or client-side balancing for those protocols.

As of 2026, Spring Cloud Kubernetes exists for teams that want Spring's discovery abstractions backed by the Kubernetes API.

Picture it Order calling http://payment-service on Kubernetes, from the DNS lookup to the pod that answers (pattern: service discovery).

Make the invisible visible: the lookup chain, with three payment pods, one of them not ready.

lookup chainruns offline
Order pod
  1. DNS: payment-service  ->  10.96.12.7          (ClusterIP, exists only in routing rules)
  2. connect 10.96.12.7:80
  3. kube-proxy / CNI rewrites destination to one ready endpoint, chosen per new connection:
        payment-7c4  10.1.1.4   ready        ✓
        payment-9fa  10.1.2.9   ready        ✓
        payment-b21  10.1.3.3   NOT ready    ✗ left out of the list

What you see: the endpoints Kubernetes currently routes to.

consoleruns offline
# illustrative output
$ kubectl get endpoints payment-service
NAME              ENDPOINTS                         AGE
payment-service   10.1.1.4:8080,10.1.2.9:8080       41d

Why: readiness decides membership, so no registry, no client library and no heartbeat code is involved. With Eureka the same view lives in a registry that every client has to fetch and refresh.

Land it Discovery moved from the application into the platform, and the remaining question is whether you need request-level balancing, which is a mesh question.

Likely follow-ups
"Explain the readiness probe's role in discovery, and what happens if it is wrong in each direction."

The readiness probe is the mechanism by which a pod joins or leaves the Service's endpoint list.

Kubernetes calls the probe every few seconds. In Spring Boot the path is typically /actuator/health/readiness.

A pod that fails it is removed from the endpoints, so no new connections are routed to it, while the pod keeps running.

The probe can be wrong in two directions:

  • Too shallow: it returns ready before the application can actually serve. Traffic arrives during startup and the first requests fail or time out. The fix is to report ready only after caches are warm and pools are open.
  • Too deep: it checks a dependency such as the database or another service. A dependency incident then removes every pod at once, the Service has no endpoints, and callers get connection refused instead of the degraded response the pods could have given.
too deep: one database incidentruns offline
# illustrative output
12:00:00  db slow  -> readiness fails on 6/6 payment pods
12:00:10  $ kubectl get endpoints payment-service
          NAME              ENDPOINTS   AGE
          payment-service   <none>      41d          ✗ callers: connection refused

The rule I use is that readiness means "this pod can take a request". Dependency health is handled inside by breakers and fallbacks.

"Show me how a Kubernetes Service actually routes a connection, and where it can go wrong."

A ClusterIP Service has a virtual IP that exists only in the cluster's packet-routing rules.

When a pod connects to it, kube-proxy — or the CNI's equivalent, such as Cilium's eBPF datapath — rewrites the destination to one of the ready pod IPs from the EndpointSlice, chosen roughly at random per new connection.

DNS resolves the service name to that virtual IP. It goes wrong in three places:

  • Per-connection choice: a client with a keep-alive pool or a gRPC channel keeps hitting the same pod.
  • Unready mid-connection: a pod that becomes unready keeps receiving requests on established connections until they close.
  • Client DNS caching: the JVM caches lookups for 30 seconds by default, which can hold on to a stale answer after a Service is recreated.
keep-alive pins a clientruns offline
# illustrative output
requests/s per payment pod, 20 order pods with keep-alive pools:
payment-7c4  ########  800      payment-9fa  #  100      payment-b21  #  100   ✗ uneven

The fixes:

  • recycle connections periodically;
  • set the JVM's networkaddress.cache.ttl low;
  • use a headless Service for clients that want to see the individual pod IPs and balance themselves.
"You mentioned zone affinity — why would you want it, and how do you get it on Kubernetes?"

Zone affinity means preferring instances in the same availability zone as the caller.

The reason is cost and latency. Cross-zone traffic in the major clouds is billed per gigabyte and adds around a millisecond.

A chatty platform can spend a meaningful part of its cloud bill on traffic between zones.

Kubernetes supports it with topology-aware routing. A Service annotation makes the endpoint slices carry zone hints, so kube-proxy prefers same-zone pods when there is enough capacity in each zone.

A mesh gives finer control, with locality-weighted load balancing that spills over to other zones only when the local ones are unhealthy.

The trade-off is balance: if one zone has fewer pods or more callers, same-zone preference overloads it, which is why the Kubernetes implementation disables itself when the pods are unevenly spread.

It is worth doing once the inter-zone bill or the latency shows up on a graph, and not before.

Q26. "What belongs in an API gateway, and what should never be put there?"

Reveal answer

Strong answer An API gateway is the single entry point for traffic from outside the platform.

It belongs doing the things every external request needs and no service should have to repeat:

  • terminating TLS;
  • validating the caller's token and rejecting unauthenticated traffic;
  • rate limiting per client;
  • routing by path or host to the right internal service;
  • request logging with a correlation id;
  • coarse response shaping such as compression.

Spring Cloud Gateway, Kong, Envoy-based gateways, and the cloud providers' managed gateways all do this.

What should never go there is business logic: composing responses from several services, transforming domain payloads, or enforcing rules such as "premium customers may see this field".

The moment the gateway knows the domain, every team's change needs a gateway change. The gateway becomes the shared, single-team bottleneck the architecture was meant to remove.

If a client needs a composed view, that is a backend-for-frontend, a small service owned by the client's team, not a gateway feature.

The other trap is a deep health check in the gateway that removes a service because its dependency is slow. The gateway should route on shallow readiness and let breakers inside services handle dependencies.

Picture it One request to GET /orders/123 through the gateway, step by step, with the jobs that do and do not belong there (patterns: API gateway, backend-for-frontend).

Make the invisible visible: the topology, with the composition job moved to the BFF.

topologyruns offline
Mobile app --> Gateway --> Order service        edge jobs only: TLS, token, rate limit, route
Web app    --> Gateway --> web BFF  --> Order, Payment, Shipping   (composes one page, owned by web team)

The trace: what the gateway does with the request.

gateway stepsruns offline
1  terminate TLS                                   ✓
2  validate JWT: signature, expiry, audience        ✓  (bad token -> 401, stops here)
3  rate limit for client-id 77: 100 req/s           ✓  (over limit -> 429, stops here)
4  route /orders/** -> order-service (shallow readiness)   ✓
5  add X-Correlation-Id, forward validated identity        ✓
6  join Order + Payment + Shipping into one JSON            ✗ belongs in a BFF
7  hide field "discount" for non-premium customers          ✗ domain rule, belongs in the service

What you see: the edge outcomes in the gateway log.

gateway access logruns offline
# illustrative output
corr=a91f client=77 GET /orders/123  token=ok      route=order-service 200  14 ms
corr=b02c client=77 GET /orders/124  token=expired -                    401   1 ms
corr=c7d4 client=78 GET /orders/125  token=ok      rate-limit           429   1 ms

Land it The gateway handles the cross-cutting edge concerns and stays ignorant of the domain, or it becomes the new monolith.

Likely follow-ups
"Where does authentication end and authorisation begin at the gateway?"

The gateway authenticates. It validates the token's signature against the identity provider's keys and checks the expiry and the audience. It rejects anything invalid with a 401 before it reaches a service.

It can also do coarse authorisation that needs no domain knowledge. For example, this route requires a token at all, or this route requires the admin scope.

What it should not do is fine-grained authorisation. Whether this user may see this order requires knowing who owns the order, and only the order service knows that.

The gateway passes the validated identity inward, typically by forwarding the token or by adding trusted headers with the subject and scopes. Each service enforces its own rules from that.

who decides whatruns offline
GET /admin/reports  token without scope admin   gateway: 403          ✓ coarse rule
GET /orders/123     token of customer 9         gateway: forwards     ✓ valid identity
                    order 123 belongs to 12     order service: 404/403 ✓ fine-grained rule

If the gateway tried to enforce "premium customers may see this field", every product change would become a gateway change, and the gateway team would become the approval step for every team's feature.

"Backend-for-frontend — what is it exactly, and who owns it?"

A backend-for-frontend is a small service whose only job is to give one type of client exactly the shape of data it needs. The client might be the mobile app, the web app or a partner integration. The BFF calls the real services and composes the result.

It is owned by the team that owns that client, which is the crucial difference from a gateway.

The mobile team can change what their app receives without asking anyone else. Their composition logic lives with the people who understand the screens.

It is the right home for the things people are tempted to put in the gateway — aggregating four calls into one, trimming fields for a small screen, translating a domain error into a user-facing message.

Its costs are one more service per client type and some duplication between them. Where a platform has only one client, a BFF and the gateway can be the same deployment, but the responsibilities stay separated in the code.

"What is a shallow versus a deep health check at the gateway, in practice?"

A shallow check asks the service whether it is alive and can accept a request. The process is up, the HTTP listener is running, and the request thread pool is not saturated.

A deep check additionally asks whether the service's dependencies, such as its database and its downstream services, are reachable. The gateway should use the shallow one.

database slow at Orderruns offline
# illustrative output
                      deep check                      shallow check
Order pods healthy    0 of 4  (all removed)           4 of 4
user gets             gateway 502                     degraded answer from Order (cached data, "try again" page, fast error)

With a deep check, a slow database makes every order pod report unhealthy and the gateway removes them all. The order service could have returned a degraded response instead.

In Spring Boot, the readiness group includes only the pieces you configure, and I keep external dependencies out of it.

The liveness group is even smaller, because a failing liveness probe restarts the pod. Restarting a pod because a dependency is slow is how one incident becomes two.

"How does the gateway rate-limit fairly across many gateway instances?"

Per-instance limits are the naive version. Each gateway pod keeps a token bucket per client and enforces, say, 100 requests a second.

The effective limit is then 100 times the number of pods, and it shifts every time the gateway scales.

effective limit by pod countruns offline
per-instance bucket 100 req/s    3 pods -> client can send 300 req/s   5 pods -> 500 req/s   ✗ drifts
shared Redis bucket 100 req/s    3 pods -> 100 req/s                   5 pods -> 100 req/s   ✓

For a real limit the counters are shared. Spring Cloud Gateway's RequestRateLimiter filter uses Redis with a token-bucket script, keyed by the client id from the token, with replenishRate and burstCapacity as the parameters.

Envoy-based gateways call a rate-limit service that does the same.

The cost is a Redis call per request, which is sub-millisecond on a local network, and a dependency on Redis.

The usual policy is to fail open, allowing the request, if Redis is unavailable. A cache outage then does not become a platform outage. An alert makes sure it is noticed.

Limits should have two tiers: a per-client fair-share limit and a global limit that protects the platform as a whole.

Q27. "What does a service mesh do, in plain words, and what does it cost? When would you skip it?"

Reveal answer

Strong answer A service mesh handles the traffic between services without any of it being in your code.

Traditionally it does this with a sidecar: a small proxy container placed beside every pod, through which all of that pod's traffic flows.

Istio's ambient mode, current as of 2026, replaces sidecars with a per-node proxy plus optional per-service proxies, which cuts the resource cost.

Through those proxies the mesh gives you, without touching application code and in any language:

  • mutual TLS between all services, with automatic certificate issue and rotation;
  • uniform timeouts and retries;
  • request-level load balancing, which fixes the gRPC connection-pinning problem;
  • traffic splitting for canaries;
  • telemetry: request rate, errors and latency per service pair.

The costs are real:

  • another control plane to operate and upgrade;
  • a few milliseconds and some memory per hop for sidecars;
  • a debugging layer between your code and the network;
  • the risk of duplicating resilience, with mesh retries multiplied by library retries.

I would skip a mesh when the platform is small (a dozen services, one language), when the team already has a shared client library that does timeouts, retries, and tracing, or when there is nobody to own the mesh. Linkerd is the lighter option; Istio the more capable one.

Picture it Order calling Payment with a sidecar mesh in between, so the application speaks plain HTTP while the proxies add mutual TLS and telemetry (pattern: sidecar and service mesh).

Make the invisible visible: where each proxy sits and what travels on the wire.

sidecar pathruns offline
[ order pod                  ]                         [ payment pod                 ]
[ order-app --http--> proxy  ] ==== mTLS, SPIFFE id ====> [ proxy --http--> payment-app ]
[   (plain HTTP, no TLS code)]   both certs verified    [   (plain HTTP)               ]
              proxy records: rate, errors, latency for order -> payment

What you see: the second container in every pod, and the memory it costs.

consoleruns offline
# illustrative output
$ kubectl get pods -n orders
NAME                 READY   STATUS    RESTARTS   AGE
order-service-7d9f   2/2     Running   0          3d      # 2/2 = app + proxy sidecar

proxy memory: ~50-100 MB per pod x 500 pods = 25-50 GB of cluster memory

Why: the proxy, not the application, terminates TLS and measures the call, so the same features work for every language. The price is the second container, the extra hop and a control plane to own.

Land it The mesh earns its keep on mTLS and multi-language uniformity; if I do not need those two, a good client library is cheaper.

Likely follow-ups
"How does mutual TLS in a mesh actually work — where do the certificates come from and how often do they rotate?"

Each workload gets an identity — in Istio, a SPIFFE identity derived from its Kubernetes namespace and service account, such as spiffe://cluster.local/ns/orders/sa/order-service.

The mesh's certificate authority issues each proxy a short-lived certificate for that identity. The default lifetime in Istio is 24 hours. The proxy renews it automatically well before expiry, so rotation is continuous and nobody manages a certificate.

When one proxy connects to another, both present certificates and both verify against the mesh's root. The connection is encrypted and authenticated in both directions. The application sends plain HTTP to its local proxy and never sees any of it.

Authorisation policies then use the identities, for example "only the checkout service account may call payment".

The failure to watch is the certificate authority being unavailable long enough for certificates to expire, which would stop all traffic. Its availability is monitored as a platform concern.

certificate lifetimeruns offline
# illustrative output
t=0h    cert issued, valid 24 h
t=~12h  proxy renews, new cert valid 24 h more        ✓ continuous rotation
CA down for 30 h:  last cert expires at t=24 h -> handshakes fail -> all service-to-service traffic stops  ✗
"What does the mesh cost in numbers — latency, memory, CPU?"

With sidecars, the typical figures I have seen and that the projects publish are roughly:

  • Latency: 0.5 to 2 milliseconds added per hop at the p50, more at the tail, because every request crosses two proxies.
  • Memory: around 50 to 100 megabytes per sidecar. At 500 pods that is 25 to 50 gigabytes of cluster memory doing nothing but proxying.
  • CPU: scales with request rate, on the order of a fraction of a core per thousand requests per second per proxy.

Istio's ambient mode, current as of Aug 2026, removes the per-pod sidecar and uses a per-node proxy for the secure transport. That cuts most of the memory cost and reduces the latency, because there is one fewer hop.

The optional per-service waypoint proxy is added only where layer-7 features are needed.

There is also the operational cost: control-plane upgrades and CRD changes. That is people rather than machines, and it is usually the bigger number.

"The platform has one language, Java, and a good client library. Why might you still want a mesh?"

Three reasons might still apply.

  1. Mutual TLS: if the security requirement is encryption and workload identity for every service-to-service call, the mesh delivers it uniformly. That includes the odd non-Java component the client library does not cover, such as a database proxy, a third-party container or a legacy service.
  2. Traffic control: canary releases by weight, traffic mirroring to a new version, and fault injection for resilience testing. A client library cannot do these because they need to sit on the receiving side.
  3. Uniform telemetry: the mesh measures every call from outside the application, so it cannot be skipped by a team that forgot to instrument. The numbers are the same for both sides of a dispute.

If none of the three is a requirement, I would keep the library, because a well-maintained library in a single language is cheaper to operate than a mesh and gives the application knowledge — such as idempotency — the mesh lacks.

"How do you keep mesh retries and library retries from doubling up, structurally?"

By writing the policy once and deriving both configurations from it, or by choosing one layer and disabling the other explicitly.

  • The explicit route: the mesh's default retry policy is set to zero attempts at the mesh-wide level. Only specific routes get mesh retries, for connection-level failures on idempotent methods. The client library keeps retries for application-level decisions.
  • The checked route: a CI check reads each service's VirtualService and its Resilience4j configuration. It fails if both define retries for the same destination.

I would also measure it. In a fault-injection test, the ratio of requests arriving at a failed dependency to first attempts from callers should be at most the configured attempts of the one layer. Any higher number means a second layer is retrying.

amplification testruns offline
# illustrative output
fault injection on tax-service, 100 first attempts from order-service
expected (library retries x3, mesh retries 0):   arrivals = 300    ratio 3.0   ✓
after mesh rollout (library x3, mesh default x3): arrivals = 900    ratio 9.0   ✗ second layer found

The rule is documented in the template, but the CI check and the test are what hold it over time.

Q28 · Scenario. "After the platform team rolled out Istio, an outage in the tax service produced nine times the normal request rate on it instead of three. Why nine?"

Reveal answer

Strong answer The number is the signature of retries at two layers.

The application's Resilience4j retry was already making three attempts.

The mesh's default retry policy sits underneath it. Istio applies two retries by default on certain error codes, so up to three attempts per request.

Each application attempt becomes up to three mesh attempts: 3 × 3 = 9.

The evidence to confirm has two parts:

  • the sidecar's access logs on the tax service side show the same request id arriving in groups of three;
  • Istio's VirtualService for tax has no explicit retry setting, so the default applies.

The fix is to choose one layer. There are two ways:

  • keep retries in the mesh, only if every team agrees to remove them from code;
  • set retries: attempts: 0 in the mesh and keep application retries, which know whether a call is idempotent. The mesh does not.

Whichever is chosen, document it in the service template.

Prevention is a platform rule that resilience policy lives in exactly one place. A fault-injection test in staging after any mesh change measures request amplification on a dependency outage.

Picture it One checkout call to the tax service while tax is down, followed attempt by attempt through the application layer and the mesh layer (pattern: retry with backoff, with the mesh as the second retrying layer).

Make the invisible visible: two layers, each with three attempts.

attempts per layerruns offline
Order app (Resilience4j, 3 attempts)
  attempt 1 -> order sidecar (mesh retry, 3 attempts) -> tax: 3 arrivals
  attempt 2 -> order sidecar                          -> tax: 3 arrivals
  attempt 3 -> order sidecar                          -> tax: 3 arrivals
                                              total on tax: 3 x 3 = 9 per user request

What you see: the tax sidecar's access log for one request id.

tax sidecar access logruns offline
# illustrative output
12:04:01.020 req-id=7f3a POST /tax/quote 503
12:04:01.095 req-id=7f3a POST /tax/quote 503
12:04:01.180 req-id=7f3a POST /tax/quote 503      <- mesh retries of app attempt 1
12:04:01.700 req-id=7f3a POST /tax/quote 503      <- app backoff, attempt 2 begins
   ... (3 groups of 3)  =>  9 arrivals, one request id

The fix: one layer keeps retries, here the application, so the mesh is set to zero for tax.

VirtualService for taxruns offline
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: tax
spec:
  hosts: [tax]
  http:
  - route:
    - destination: {host: tax}
    retries:
      attempts: 0        # ✅ FIX: the application layer owns retries

What you see now: the same log after the change.

tax sidecar access logruns offline
# illustrative output
12:09:01.020 req-id=9c1e POST /tax/quote 503
12:09:01.530 req-id=9c1e POST /tax/quote 503      <- app attempt 2 after backoff
12:09:02.540 req-id=9c1e POST /tax/quote 503      <- app attempt 3
   =>  3 arrivals, one request id

Land it Retries multiply across layers, and the layer that should keep them is the one that knows whether the call is safe to repeat.

Likely follow-ups
"You set mesh retries to zero and it is still six times, not three. What next?"

Six is two times three. Either there is still one more layer retrying twice, or one of the three layers has an attempts value I did not expect.

I would trace a single failing request end to end. I count its arrivals at the tax service by request id, then look at which hop produced each copy.

counting copies by hopruns offline
# illustrative output
req-id=5d20  arrivals at tax: 6   = 3 (app attempts) x 2 (someone else)
  header x-forwarded-by: edge-gateway on 3 of 6 copies   -> gateway retries? 
Candidates to read, not assume:  gateway retry config, HTTP client retry handler, upstream service

The candidates:

  • The gateway in front of the platform, which often has its own retry defaulting to one or two attempts on 5xx.
  • An HTTP client library's built-in retry, such as Apache HttpClient's default retry handler, which retries idempotent requests a few times independently of Resilience4j.
  • The tax service's own upstream, which retried its calls.

Each one is checked by reading its configuration, not by assuming.

The general point is that retry layers accumulate silently — a proxy here, a library default there — and the only reliable way to find them all is to count arrivals for one request in a controlled fault-injection test.

"Which errors does Istio retry by default, and why does that matter for idempotency?"

As of Aug 2026, Istio's default is two retries on a set of conditions that are mostly connection-level: connect failures, refused streams, and the gRPC "unavailable" and "cancelled" codes, plus 503 responses in the default set.

The important detail is that Envoy, which does the retrying, does not know whether a POST is safe to repeat.

  • Connect failure: safe to retry for any method, because the request was never delivered.
  • A 503 or a reset after the request was sent: not safe, because the server may have processed it before the connection dropped.
POST /payments through the meshruns offline
# illustrative output
attempt 1  payment received POST, charged card, connection reset before response   ✗
attempt 2  mesh retries same POST (no idempotency key seen by the mesh)
           payment charges again                                                    ✗ double charge
the application layer never sees attempt 2

So a mesh retry policy applied uniformly can duplicate a non-idempotent call, and the application layer never sees that it happened.

That is why my preference is to keep mesh retries only for the pre-delivery failure conditions. Every retry that happens after a request was delivered stays with the application, which can attach an idempotency key.

"How do you decide, as a platform rule, which layer keeps retries?"

I write the decision as a table with two rows and stick to it.

Which layer retries what
LayerRetriesCondition
MeshConnection refused, connection reset before any bytes were sent, a refused streamThese prove the request was not delivered. Safe for any method, and the mesh sees them most reliably.
ApplicationEverything else: timeouts, 503s, 429sOnly for calls classified as idempotent, with a key where needed and with a budget.

The reason for that split is knowledge: the mesh knows the transport and nothing about the semantics; the application knows the semantics.

The rule goes into the service template so a new service's Resilience4j configuration and its VirtualService are generated consistently, and a monthly fault-injection test on a sample dependency verifies the total amplification is what the table predicts. Any team wanting an exception has to show a measurement.

"How did you get to nine so quickly — what did you look at first?"

The arithmetic. Nine is three squared, and the application's retry configuration was known to be three attempts.

A multiple that is a clean product of small integers points at layered retries. A traffic spike would give an arbitrary number.

So the first thing I checked was the sidecar's access log on the tax service, filtered by one request id from the incident window.

The log showed three arrivals with the same id within a few hundred milliseconds, which are the mesh's retries. It then showed three such groups, spaced by the application's backoff.

That pattern confirms both the layer and the timing.

The second check was whether the VirtualService for tax had a retries block. It did not, so Istio's default applied.

From there, the fix is a configuration change, and the postmortem question is why the mesh rollout did not include a retry-policy review.

Q29 · Design. "For an order system, decide sync or async for each of these: price lookup, charge card, reserve stock, send confirmation email, update the search index. Justify each."

Reveal answer

Strong answer The rule I apply: synchronous when the caller cannot continue without the answer and the user is waiting; asynchronous when the caller can record intent and move on.

  • Price lookup: synchronous, because checkout cannot proceed without a price and a stale one is a business error. It is cached locally with a breaker and a fallback to "re-price at payment".
  • Charge card: synchronous from the user's point of view, because they need to know it worked. It is implemented as a saga step with an idempotency key. A "pending" outcome is allowed when the payment provider is slow, so the order is recorded and completed by an event later.
  • Reserve stock: asynchronous via an event from the order's outbox in most retail systems, because overselling by a few units is tolerable and compensated. It is synchronous only for scarce inventory such as event tickets, where a reservation must be confirmed before charging.
  • Confirmation email: asynchronous, always. It is a queue with retries and a dead-letter destination, because nobody should wait on an SMTP server.
  • Search index: asynchronous, consuming the same order and product events. The index is a read model and a few seconds of lag is invisible.

The trade-off is that async steps need the outbox, idempotent consumers, and a way to show the user "processing" states.

Picture it One order placed on the platform, showing which hops the customer waits on and which happen later through the broker (patterns: outbox, saga, dead-letter queue).

Make the invisible visible: lanes per service, solid arrows are waited on, the broker lane is not.

sync and async hopsruns offline
Customer | Order        | Pricing | Payment | Broker      | Inventory | Email / Search
POST --> | price?  ---> | 19.99   |         |             |           |               sync, 60 ms
         | charge  ------------> | ok/pending|             |           |               sync, <= 5 s
         | row in orders + outbox (one DB transaction)    |           |
<-- 201 "order received"                                  |           |               customer stops waiting
         | relay -----------------------> OrderPlaced --> | reserve   |               async
                                                 \------------------------------>  | send mail, index  async

What you see: the order as the customer sees it when payment is slow, and what is stored.

order rows and statusruns offline
# illustrative output
POST /orders  -> 201 {"orderId":"o-881","status":"PAYMENT_PENDING"}     ✓ no error, no timeout

orders:  o-881 | PAYMENT_PENDING
outbox:  id=e-1 | OrderPlaced | published=false     -> becomes true when the relay publishes
later:   PaymentCompleted -> status PAID -> email sent when status = CONFIRMED

Land it Only the two decisions the user is waiting on stay synchronous, and even those are shaped so that a slow dependency yields a pending state instead of an error.

Likely follow-ups
"The requirement changes: it is a ticketing site and every item is scarce. What moves?"

Reserve stock moves to synchronous and becomes the first step. For scarce inventory a reservation is the product: the customer must hold the seat before paying. Overselling is not a small compensation but a public failure.

The order becomes:

  1. Reserve synchronously with a time-limited hold, ten minutes, enforced by the inventory service's own expiry.
  2. Price and charge within that window.
  3. Confirm the reservation on payment success.

The reservation call is idempotent on the order id, so a retry cannot double-hold.

Everything downstream of the charge, such as email, search index and analytics, stays asynchronous.

The saga changes shape too. Releasing a hold is the first compensation and is cheap, while the charge stays late so a refund is rare.

Under load, the synchronous reservation becomes the contended path. It gets a bulkhead and a queueing strategy, a waiting room, rather than being allowed to fail randomly.

"Charge card is synchronous but you also said it is a saga step with a pending outcome. Reconcile that."

The user waits on the answer, so the request is synchronous from their point of view. The implementation allows three outcomes rather than two: success, failure, and pending.

Checkout calls payment with an idempotency key and a bounded timeout, say 5 seconds.

  • Success: it returns the confirmed order.
  • Definite failure (declined): it returns the error and the saga compensates.
  • Timeout or provider "processing" status: it records the payment attempt as pending and returns "order received, payment processing" to the user. A background step resolves it. The payment service's outbox emits PaymentCompleted or PaymentFailed when the provider's result arrives, and the order advances or compensates from that event.
payment attempt table over timeruns offline
# illustrative output
t=0s   payments: key=o-881-1 | PENDING            checkout times out at 5 s -> user sees "payment processing"
t=9s   provider callback: approved
t=9s   payments: key=o-881-1 | COMPLETED ; outbox: PaymentCompleted
t=10s  orders:   o-881 | PAID  -> email on CONFIRMED

A slow provider degrades the experience: the user sees a pending state. It does not produce a timeout error, a double charge, or a thread held for a minute.

The user gets the confirmation by email or on the next page load.

"Under time pressure, which of these would you make synchronous just to ship, and what would that cost later?"

The confirmation email and the search-index update are the ones teams make synchronous to avoid building the outbox and the consumers. It works on day one.

The costs arrive quickly:

  • the checkout's latency includes an SMTP round trip, so a slow mail provider makes checkout slow;
  • a mail provider outage produces checkout errors for orders that were actually placed, and the retry doubles emails;
  • the search index becomes part of checkout's availability.

If I had to ship without the broker, I would still not call them inline.

I would write the email and index jobs as rows in a local job table in the order transaction and run a simple in-process scheduler over it. That is a poor man's outbox. It is a day's work and turns into the real outbox later by pointing the relay at Kafka.

job table in the order transactionruns offline
# illustrative output
one DB transaction:  orders  o-881 | PLACED
                     jobs    j-1 | SEND_EMAIL  | o-881 | status=NEW
                     jobs    j-2 | UPDATE_INDEX| o-881 | status=NEW
scheduler every 5 s: pick NEW jobs -> run -> status=DONE (retry on failure, no SMTP in checkout)

What I would never defer is the idempotency key on the charge, because that is the difference between a bug and a double charge.

"How does the user see the state of the asynchronous steps?"

Through explicit states in the order, not through the absence of errors.

The order has a status the read model maintains from events: placed, payment processing, paid, reserving stock, confirmed, and the failure states. The order page renders whichever it is with a plain-language message.

The confirmation page after checkout shows "order received" with the order number immediately, plus the payment status as it stands.

It either polls a status endpoint every few seconds or receives a push.

The email is sent when the order reaches confirmed, not when it is placed, so the customer never gets an email for an order that then fails.

For operations, the same states feed a dashboard of orders per state and the age of the oldest order in each, because an asynchronous step that has silently stopped shows up there as an ageing pile long before a customer complains.

Q30. "When would you NOT use gRPC, even between internal services?"

Reveal answer

Strong answer I would keep REST in a few specific cases:

  • Browsers or outside partners: when the consumers include browsers or partner teams outside my control, because gRPC needs a translation proxy for browsers and asks partners to adopt protobuf tooling.
  • HTTP-shaped debugging: when the operations team uses curl, browser dev tools and log inspection of readable payloads, and the latency gain would be a few milliseconds nobody would notice.
  • Connection-level load balancing: when the platform's load balancer balances connections rather than requests and there is no mesh. gRPC's long-lived HTTP/2 connections then pin each client to one server and defeat scaling. I have seen teams add gRPC and lose their load balancing at the same time.
  • HTTP caching or a resource model: when the API benefits from HTTP caching or from being an evolving resource model that many clients navigate.
  • Small team: one wire format is one less thing to own.

gRPC wins clearly for high-volume internal calls, streaming, and polyglot platforms where generated clients save real effort.

The senior point is that gRPC is still synchronous. The failure arithmetic is identical to REST: availability multiplies and threads wait.

The sync-versus-async decision matters far more than the wire format.

Picture it Twenty Order pods calling three Payment pods over gRPC behind a connection-level Kubernetes Service, before and after request-level balancing (related: service discovery).

The setup: a channel that dials the ClusterIP, so every Order pod keeps one long-lived HTTP/2 connection.

Order pod gRPC channelruns offline
// ❌ TRAP: dials the virtual IP, one connection is picked once and reused for every call
ManagedChannel pinned = ManagedChannelBuilder
    .forTarget("dns:///payment-service:9090").usePlaintext().build();

// ✅ FIX: headless Service returns all pod IPs, client balances per request
ManagedChannel balanced = ManagedChannelBuilder
    .forTarget("dns:///payment-headless:9090")
    .defaultLoadBalancingPolicy("round_robin")
    .usePlaintext().build();

What you see: requests per second on each Payment pod.

per-pod request rateruns offline
# illustrative output
                 payment-7c4   payment-9fa   payment-b21
pinned (ClusterIP)     820           95            85        ✗ one pod does the work, adding pods changes nothing
round_robin (headless) 330          340           330        ✓ requests spread across all three

Why: the Service balances new connections, and gRPC opens very few. Round robin in the client balances each request instead.

Land it I would choose gRPC for throughput and contracts, and skip it whenever it would cost me load balancing, debuggability, or a consumer I cannot change.

Likely follow-ups
"You said gRPC can lose load balancing. How would you detect that has happened and fix it without a mesh?"

Detection is a per-pod request-rate graph on the server side. With connection pinning, a few pods show high traffic and the rest near zero, and adding pods does not change the busy ones.

adding a pod changes nothingruns offline
# illustrative output
before scale-up (3 pods):  820 /  95 /  85 req/s
after  scale-up (4 pods):  815 /  90 /  80 /  0 req/s    ✗ the new pod gets no connections

The fix without a mesh is client-side load balancing in the gRPC client:

  1. Point the channel at a headless Kubernetes Service, so DNS returns all pod IPs rather than one virtual IP.
  2. Set the channel's load-balancing policy to round_robin. The client then opens a sub-channel per backend and rotates requests across them.
  3. Let the client re-resolve DNS as pods change. The gRPC Java resolver does this on connection failures and on a refresh interval.
  4. On the server, set a maximum connection age of a few minutes. That forces periodic reconnection, so new pods eventually receive traffic even from clients that were pinned.

Together these give request-level balancing with no proxy, at the cost of the client holding one connection per backend.

"How do you debug a gRPC call in production when the payload is binary?"

With tooling that knows the schema.

grpcurl is the equivalent of curl. It uses server reflection or the proto files to let you call a method and see the response as JSON.

grpcurlruns offline
# illustrative output
$ grpcurl -plaintext -d '{"orderId":"o-881"}' payment-headless:9090 payments.Payment/GetStatus
{ "orderId": "o-881", "state": "COMPLETED" }

For traffic inspection, the mesh sidecar or Envoy access logs give method, status code, and latency without decoding bodies. That is usually enough.

For bodies, I log at the application level with the generated message's JSON printer, JsonFormat.printer() in Java. It is at debug level and behind a sampling flag, never every message.

Tracing carries the method name and status as span attributes, so a failed call is found by status rather than by reading bytes.

For a wire-level capture, Wireshark decodes gRPC over HTTP/2 when given the proto files.

The habit that has to change is reaching for the browser's network tab; the replacement is a small set of command-line tools that the platform team installs in every engineer's environment.

"Is there a middle ground between REST and gRPC for internal calls?"

Yes, and it is often the pragmatic choice.

The largest gains of gRPC are the contract and the generated client. REST can have both:

  • generate the client and server stubs from an OpenAPI document;
  • check the document for breaking changes in CI, using tools such as openapi-generator and an OpenAPI diff check.

HTTP/2 multiplexing is available to REST clients as well. Java's HttpClient and Spring's RestClient over it will use HTTP/2 when the server supports it.

Binary encoding can be added selectively, using a compact JSON alternative or protobuf over HTTP for the one or two high-volume endpoints.

What this hybrid does not give is streaming and native deadline propagation, which are the cases where I would move that specific path to gRPC. The point I would make is that the contract discipline matters more than the transport, and it can be applied to either.

Drill · Asynchronous messaging with Kafka

This group tests whether you know what a broker actually promises — ordering, delivery, rebalancing — and the failure modes that follow from each promise.

Q31. "Kafka versus RabbitMQ: what is the structural difference, and which do you pick for which job?"

Reveal answer

Strong answer RabbitMQ is a message queue.

  1. A producer sends a message.
  2. The broker routes it through exchanges and bindings to one or more queues.
  3. A consumer takes it and acknowledges it.
  4. The broker deletes it.

Its strengths are rich routing, per-message acknowledgement, and simple work distribution.

Kafka is a distributed, partitioned, replicated log. Messages are appended to a partition in order and kept for a configured retention (days, or forever with compaction).

Consumers track their own position, the offset. So many independent consumer groups can read the same stream, and any of them can rewind and replay.

Its strengths are throughput (millions of messages a second across a cluster), replayability, and being the shared record several services build read models from.

My picks:

  • Kafka: event streams that more than one service cares about, anything needing replay or audit, and change data capture.
  • RabbitMQ or a cloud queue such as SQS: work queues, such as send this email or generate this report. Each job must be done once by one worker, per-message retry and dead-lettering matter, and the volume is thousands rather than millions a second.

Since Kafka 4.0 (March 2025) it runs without ZooKeeper, using KRaft, which simplified operating it considerably.

Picture it The same three OrderPlaced messages in a queue and in a log, after two different consumers have read them (related: dead-letter queue for the queue side).

Make the invisible visible: what is left in each system and who remembers what.

queue versus logruns offline
RabbitMQ queue "email-jobs"                 Kafka topic orders, partition 0
 before: [m1][m2][m3]                        offset: 0   1   2
 worker takes m1, acks -> m1 deleted          log:   [m1][m2][m3]     (kept for retention)
 after:  [m2][m3]                            group "search":  position 3  (read all)
 one worker gets each message                group "analytics": position 1 (read m1 only)
                                             group "analytics" rewinds to 0 -> reads m1,m2,m3 again

What you see: the consumer-side state after the same traffic.

consoleruns offline
# illustrative output
RabbitMQ  messages_ready=2  messages_unacked=0     # m1 is gone, nothing to replay
Kafka     GROUP      TOPIC   PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG
          search     orders  0          3               3               0
          analytics  orders  0          1               3               2

Why: a queue forgets a message once it is acknowledged, so it suits one worker per job. A log keeps it and each group keeps its own bookmark, so it suits several readers and replay.

Land it If several consumers need the same history, it is a log and that means Kafka; if one worker needs each job once, it is a queue.

Likely follow-ups
"Why is Kafka a poor work queue? Be specific about what breaks."

Three things break.

  1. Per-message acknowledgement: Kafka commits an offset, not a message. If message 5 in a partition fails and message 6 succeeds, you cannot acknowledge 6 without also implying 5. You either block the partition on 5 or move 5 aside to a retry topic.
  2. Fair distribution: work is spread by partition, not by message. With twelve partitions you can have at most twelve active workers. A slow job on one partition delays everything behind it while other workers idle.
  3. Delayed and prioritised delivery: a queue can hold a job for an hour or move an urgent one ahead. A log delivers in append order, so delays are implemented with separate topics per delay tier and consumers that sleep.
offset versus message ackruns offline
partition 0:  offset 5 = send-email(o-1)  fails    offset 6 = send-email(o-2)  ok
commit offset 7?  -> implies 5 was handled                            ✗ o-1 lost
do not commit    -> 6 is redelivered with 5 (duplicate)             ✗
queue (SQS/RabbitMQ): ack 6 alone, 5 stays for retry / DLQ           ✓

RabbitMQ or SQS give all three natively, with per-message retry counts, visibility timeouts, and dead-letter queues.

Kafka can be made to do it. Every one of those features is something the team builds and operates.

"What did KRaft change in practice for someone operating Kafka?"

Before KRaft, a Kafka cluster needed a separate ZooKeeper ensemble for metadata — which broker leads which partition, the topic configurations, the controller election.

That meant two distributed systems to run, monitor, upgrade, and secure.

It also put a ceiling on partition count, because controller failover had to reload metadata from ZooKeeper. That took minutes at hundreds of thousands of partitions.

KRaft moves the metadata into a Raft-replicated log inside Kafka itself. A small set of controller nodes manages it, and they can be dedicated or combined with brokers.

In practice that had three effects:

  • it removed one system from the on-call rotation;
  • it made controller failover nearly instant, because the standby controllers already hold the metadata;
  • it raised the practical partition limit into the millions.

Since Kafka 4.0 in March 2025, ZooKeeper mode is gone entirely, so any cluster still on it has to migrate before upgrading; the migration is a documented, online procedure but it needs to be planned.

"What about a cloud queue instead of RabbitMQ — SQS, Pub/Sub — how does that change the choice?"

For the work-queue role a managed queue is usually the better pick than self-hosted RabbitMQ. The operational cost falls to almost nothing and the semantics are the ones you want.

SQS gives visibility timeouts, per-message retry counts, dead-letter queues, and FIFO queues with deduplication for the cases that need ordering.

The trade-offs are limits — message size around 256 kilobytes, FIFO throughput caps per message group — and a per-request price that matters at tens of thousands of messages a second.

For the event-stream role, the managed equivalents of Kafka are managed Kafka itself — MSK, Confluent Cloud — or a different model such as Pub/Sub or Kinesis, and the question becomes whether you need Kafka's ecosystem: Connect, Streams, the schema registry, replay by offset.

My rule in a cloud-hosted platform is a managed queue for jobs, managed Kafka for the shared event log, and a strong reason before running either myself.

"You have Kafka already. A team wants RabbitMQ for one job queue. Do you let them?"

I would ask what the job queue needs that Kafka cannot give cheaply.

If the answer is per-message retry with delays, priorities, or thousands of independent small jobs, those are real gaps, and the honest choice is between adding a second broker and building those features on Kafka.

A second broker is another system to operate, secure, monitor, and keep in the disaster-recovery plan, and if only one team uses it, it will be the least understood system on the platform.

So my preference is a managed queue service rather than self-hosted RabbitMQ if the platform is in a cloud, because that gets the semantics without the operations.

If it must be self-hosted, the platform team owns it as a shared service, not the requesting team, and it needs at least two consuming teams before it is worth its keep. What I would not do is let each team pick its own broker.

Q32. "What ordering does Kafka guarantee, exactly, and how do you get 'all events for one order in order'?"

Reveal answer

Strong answer Kafka guarantees order within a partition and nothing across partitions. A topic with twelve partitions is twelve independent ordered logs.

The producer chooses the partition by hashing the message key. Messages with the same key always land on the same partition and are appended in the order the producer sent them.

So "all events for order 123 in order" means: use the order id as the message key, and produce those events from one producer in sequence.

Four more conditions matter:

  1. Idempotent producer: enable.idempotence=true (the default since Kafka 3.0) guarantees that retries by the producer itself do not reorder or duplicate within a partition.
  2. In-flight limit: max.in.flight.requests.per.connection must be at most 5 with idempotence on, which is enforced.
  3. Sequential consumer: order is preserved only if one consumer thread handles a partition sequentially. A consumer that fans out messages to a worker pool loses ordering unless it partitions the pool by key too.
  4. One topic: ordering across two topics, such as "OrderCreated" on one and "PaymentCompleted" on another, is not guaranteed at all. Related events for one aggregate belong on one topic.

Picture it Events for orders 123 and 456 on a 4-partition topic, with a key and without one, and what a naive worker pool does to the order (the producer side of the outbox relay depends on this).

Make the invisible visible: where each event lands.

key to partitionruns offline
# illustrative output  (partition = hash(key) mod 4)
key=123  OrderCreated -> p1 offset 7     key=123  PaymentCompleted -> p1 offset 8    key=123  Shipped -> p1 offset 9   ✓ one log, in order
key=456  OrderCreated -> p3 offset 2     key=456  OrderCancelled   -> p3 offset 3
no key:  OrderCreated(123) -> p0   PaymentCompleted(123) -> p2   Shipped(123) -> p1                                    ✗ three logs, no order

The trace: a consumer that hands partition 1 to a thread pool.

worker pool interleavingruns offline
poll():   [123 Created][123 Paid][123 Shipped]       all from partition 1, in order
thread A takes "123 Created"   (slow, 300 ms)
thread B takes "123 Paid"      (fast, 20 ms)  -> Paid applied before Created   ✗
thread C takes "123 Shipped"   -> Shipped applied before Paid                  ✗
fix: worker = hash(key) mod 3  -> all of 123 on one worker, in order           ✓

What you see: the consumer log.

consumer logruns offline
# illustrative output
p1@8  key=123 PaymentCompleted  -> order 123 not found, stored as pending   ✗ out of order
p1@7  key=123 OrderCreated      -> applied

Land it Ordering is a property of the key, the partition, and a single sequential consumer, and it is lost the moment any of the three is changed carelessly.

Likely follow-ups
"What does the idempotent producer actually do on the wire, and what does it not protect against?"

With enable.idempotence=true, the producer gets a producer id from the broker. It attaches a sequence number per partition to every batch it sends.

The broker keeps the last sequence numbers per producer per partition.

  • It rejects a batch whose sequence it has already written. A retry of a batch that was persisted but whose acknowledgement was lost does not produce a duplicate.
  • It rejects a batch arriving out of sequence, rather than appending it out of order.
sequence numbers on the wireruns offline
# illustrative output
producer id=77, partition 1
send batch seq=5  -> broker appends, ack lost          (network drop)
retry batch seq=5 -> broker: already have seq 5 -> not appended, ack returned   ✓ no duplicate
send batch seq=7 (seq 6 missing) -> rejected, not appended out of order         ✓

That is why up to five in-flight requests are allowed without losing order.

What it does not cover:

  • Application-level duplicates: the application calling send() twice, for example the outbox relay re-sending after a crash. From the broker's point of view those are two different messages.
  • Producer restarts: a new producer instance gets a new producer id.

Those need the event id in the message and an idempotent consumer.

"The consumer needs more throughput than one thread per partition gives. How do you parallelise without losing order?"

By partitioning the work inside the consumer by the same key.

The consumer thread reads a batch from its partitions. It dispatches each record to a worker chosen by hashing the record's key over a fixed pool of workers.

All records for order 123 always go to worker 7 and are processed in order. Records for other orders run on other workers in parallel.

keyed dispatchruns offline
# illustrative output  (worker = hash(key) mod 8)
123 Created  -> worker 7 \
123 Paid     -> worker 7  > in order on one worker
456 Created  -> worker 2   (parallel with the 123 events)
committed offset = highest offset with every earlier record on the partition finished

Offsets are committed only up to the point where every earlier record on that partition has completed. That needs a small bookkeeping structure per partition.

Confluent's parallel-consumer library implements exactly this with key-level ordering, and Spring Kafka can approximate it with a batch listener and a keyed executor. The alternative is more partitions and more consumer instances, which is simpler but is bounded by the partition count and costs a rebalance.

The thing to avoid is a plain thread pool, which destroys the ordering the key was chosen to keep.

"How does compaction interact with ordering, and what is a tombstone?"

A compacted topic keeps, for each key, at least the latest message. A background cleaner removes older messages for that key.

Order within a partition is still preserved among the messages that remain. A consumer reading from the beginning sees the latest state of each key in an order consistent with the original writes.

compaction and a tombstoneruns offline
# illustrative output
before: 0:k123=Created  1:k456=Created  2:k123=Paid  3:k123=null (tombstone)
after:  1:k456=Created  3:k123=null
after delete.retention.ms (default 1 day): 1:k456=Created        # tombstone removed too

A tombstone is a message with a key and a null value. It tells the compactor to delete all earlier messages for that key.

The tombstone itself is kept for a configured period, delete.retention.ms, one day by default. Consumers that are behind can see the deletion before it disappears.

The gotcha is that a consumer that starts more than that period after the tombstone never learns the key was deleted. A local copy built from a compacted topic can hold keys the owner has removed.

For reference data that is rarely deleted this is fine; for anything else the copy needs a periodic full reconciliation.

"Why would events for one aggregate on two topics be a problem — cannot the consumer sort by timestamp?"

It cannot rely on timestamps, for two reasons.

  1. Clocks: producer timestamps come from the producer's clock, so two events written by different services a millisecond apart can carry timestamps in the wrong order. Broker timestamps reflect append time on different partitions on different brokers, which is not the causal order either.
  2. Independent streams: the consumer sees the two topics through two streams with independent lag.
two topics, two lagsruns offline
# illustrative output
12:00:00.000  PaymentCompleted(123)  written to topic payments
12:00:00.010  OrderCancelled(123)    written to topic orders
payments lag 3 s, orders lag 0 s  ->  consumer sees OrderCancelled first, PaymentCompleted 3 s later
timestamp sort would help only if it saw both events at once; it must decide as each one arrives   ✗

The consumer has to decide what to do at the moment it sees each event, regardless of their timestamps.

So the honest options are: put all events for one aggregate on one topic with the aggregate id as key, which gives order for free; or design the consumer to be order-independent, storing each event and computing state from the set. Sorting by timestamp is neither.

Q33 · Scenario. "After the platform team increased the orders topic from 6 to 12 partitions to add capacity, the inventory service began processing 'OrderCancelled' before 'OrderCreated' for some orders. Explain."

Reveal answer

Strong answer Adding partitions changes the hash-to-partition mapping. Before the change, order 123's key hashed to partition 4; after it, the same key hashes to partition 9.

Events produced before the change sit on partition 4 and events produced after sit on partition 9.

An order created just before the repartition and cancelled just after has its two events on two different partitions. Two different consumers read them, with no ordering between them.

The evidence has two parts:

  • timestamps of the affected orders cluster around the repartition;
  • the two events have different partition numbers in the consumer logs.

The fix for the data is to make the consumer tolerant. An "OrderCancelled" arriving for an unknown order is stored as a pending cancellation and applied when the "OrderCreated" arrives. That is a good idea regardless.

The prevention is to treat partition count as a permanent decision. There are two parts:

  • Over-provision from the start: 30 or 60 partitions for a topic expected to grow.
  • If a change is unavoidable: drain the topic (stop producers, let consumers catch up to the end, then repartition), or create a new topic and migrate.

The senior detail: this also breaks the outbox relay's assumption that a key stays on one partition. Any exactly-once reasoning keyed on partition must be re-examined.

Picture it Order 123's two events before and after the topic grows from 6 to 12 partitions, and what Inventory sees (the producer is the outbox relay).

Make the invisible visible: the key-to-partition mapping changes with the partition count.

key to partition before and afterruns offline
# illustrative output  (partition = hash(key) mod partition-count)
key=123 hash = ...10                 6 partitions: 10 mod 6  = 4
                                    12 partitions: 10 mod 12 = 10     (a key on 4 of 6 can only move to 4 or 10 of 12)
t=12:00:00  OrderCreated(123)   -> partition 4  offset 881     (6 partitions)
t=12:00:05  topic grows to 12 partitions
t=12:00:09  OrderCancelled(123) -> partition 10 offset 12      (12 partitions)

The trace: two consumers, two partitions, no ordering between them.

Inventory consumersruns offline
consumer-A (partition 4)   lag 3 s   ... reads OrderCreated(123)   at 12:00:12
consumer-B (partition 10)  lag 0 s   reads OrderCancelled(123)     at 12:00:09   ✗ cancel arrives first

What you see: the evidence in the Inventory log.

Inventory logruns offline
# illustrative output
12:00:09 WARN  OrderCancelled order=123 p=10@12  -> unknown order, no stock to release
12:00:12 INFO  OrderCreated   order=123 p=4@881  -> stock reserved                    ✗ reserved for a cancelled order

The fix: a tolerant consumer stores the early cancellation and applies it when the creation arrives.

pending cancellationruns offline
12:00:09 OrderCancelled order=123  unknown -> store pending_cancellations(123)
12:00:12 OrderCreated   order=123  -> find pending cancellation -> do not reserve, mark CANCELLED   ✓

Land it Partition count is part of the ordering contract, and I plan it for the topic's lifetime rather than its first month.

Likely follow-ups
"You made the consumer tolerate a cancellation before creation. What if an event is not merely early but never arrives?"

Then the pending cancellation waits forever, and I need a bound and an owner.

The consumer stores the orphan with a received-at timestamp. A sweeper looks for orphans older than a threshold, a few minutes, well beyond any normal lag.

For each one it does not guess; it asks the owner. A call to the order service for order 123 returns its current state, and the consumer applies that state directly. That also covers the missing-creation case.

  • Owner returns the order: apply its state.
  • Owner has never heard of the order: the event was for something that failed before it was committed. The orphan is discarded with a log line.
  • Owner unreachable: the sweeper tries again later, up to a limit, then raises an alert.
orphan sweeperruns offline
# illustrative output
pending_cancellations: order=123 | received_at=12:00:09
12:05:10 sweeper: 123 older than 5 min -> GET order-service/orders/123
         200 CANCELLED  -> apply, delete orphan                       ✓
         404            -> discard orphan, log line                    ✓
         timeout        -> retry later (max 5), then alert             ✓

That pattern — store, wait briefly, then reconcile against the source of truth — is how I handle any "event arrived out of context" case, because the alternative of dropping or guessing produces silent inconsistency.

"How would you have done the capacity change safely?"

The safe procedure is a drain:

  1. Stop the producers. In practice, pause the outbox relays that feed the topic, so events accumulate in the outbox tables rather than being lost.
  2. Wait until lag is zero for every consumer group on the topic. The lag metric shows this in seconds.
  3. Add the partitions.
  4. Resume the producers.
drain procedureruns offline
# illustrative output
12:00:00 relay paused      outbox: published=false rows accumulate (e-901, e-902, ...)
12:00:20 lag orders: inventory-group 0, search-group 0           ✓ nothing unconsumed on old partitions
12:00:21 partitions 6 -> 12
12:00:25 relay resumed     key 123 -> partition 10 for all new events, no old events outstanding   ✓

Every key now hashes to its new partition, but there are no old events of the same key still unconsumed on the old partitions. No consumer sees a key on two partitions. The pause is typically under a minute.

The alternative, when a pause is unacceptable, is a new topic with the desired partition count. Producers switch to it. Consumers subscribe to both, finish the old one, and unsubscribe from it.

Either way the change is announced, scheduled, and done by someone who knows the ordering contract — not as a routine capacity tweak by a platform script.

"Why not choose a very large partition count from the start — what does it cost?"

Partitions are not free. Each partition costs:

  • Broker files: a set of files with its own index and open file handles.
  • Replication: a leader and followers in the replication protocol. A cluster with hundreds of thousands of partitions spends real CPU on replication heartbeats and leader elections, and a broker restart takes longer because every partition's leadership has to move.
  • Consumer overhead: a slot in every consumer's fetch requests. More partitions than consumers is fine, but a topic with 600 partitions and one consumer instance makes that instance fetch from 600 sources and commit 600 offsets, which adds latency and memory.
  • Producer batching: each batch is per partition, so a spread-out write fills batches slowly.

So I pick a number with headroom for the expected growth — say three to five times the initial consumer count — and I treat going beyond that as a planned migration, not a default.

"Does the same problem affect the outbox relay's ordering, and how?"

Yes. The relay preserves ordering per aggregate by sending all of an aggregate's events with the same key. It relies on the key-to-partition mapping being stable.

After a repartition, an aggregate's earlier events sit on the old partition and its later ones go to the new. A consumer can see them in either order, which is exactly the scenario.

The relay itself has a second exposure. If it is mid-way through a batch during the repartition, part of the batch lands on the old mapping and part on the new. Even one batch's events for a key can straddle partitions.

Beyond ordering, any consumer logic that assumes "all of this key's events are on my partition" is broken by the change. A local de-duplication cache keyed by partition is an example. It must be keyed by event id instead.

So I re-examine every place partition identity is used as a proxy for key identity, and I prefer designs that only rely on the event id.

Q34. "What is a consumer group rebalance, what happens to in-flight messages during one, and what changed in recent Kafka to make it less painful?"

Reveal answer

Strong answer A consumer group is a set of consumer instances that share a topic's partitions between them, each partition to exactly one member.

A rebalance is the redistribution that happens when:

  • a member joins, leaves or crashes;
  • a member fails to heartbeat within session.timeout.ms;
  • a member takes longer than max.poll.interval.ms to process a batch.

In the classic protocol every member stops consuming, gives up all partitions, and receives a new assignment. That is a stop-the-world pause of seconds.

Messages that a consumer had fetched but not yet committed the offset for are simply reassigned to another member. It reads them again from the last committed offset. That is where duplicate processing after a rebalance comes from, and why consumers must be idempotent.

Two changes made rebalances less painful:

  • Cooperative-sticky assignor (Kafka 2.4+): rebalances are incremental, moving only the partitions that need to move.
  • New consumer group protocol (KIP-848, Kafka 4.0): the broker computes assignments and members are told individually, so a rebalance no longer stops the whole group. As of 2026 it is the default for new clients.

The practical rule: keep processing per poll short, commit offsets after the work commits, and never rely on "this partition is mine" without checking the assignment.

Picture it Two inventory consumers, A and B, when a rebalance moves a partition from A to B in the middle of a batch (guard against the resulting duplicates with the idempotent consumer).

Make the invisible visible: partition 2 with its committed offset and the batch A was working on.

committed offset and batchruns offline
partition 2:   ... 98  99 [100 101 102 103 104] 105
                         ^ committed offset = 100        [ ] = batch A fetched, processing 101

The trace: time-ordered steps.

rebalance interleavingruns offline
t0  A: poll() -> records 100..104, processes 100, 101 (DB commits done)
t1  B joins the group -> rebalance, partition 2 moves to B
t2  B: starts at committed offset 100 -> processes 100, 101 again           ✗ duplicate effects
t3  A: finishes batch, commitSync() -> CommitFailedException (not the owner) ✗

What you see: the evidence for the duplicate.

consumer logsruns offline
# illustrative output
A  12:00:03 INFO  reserved stock order=101 offset=101
B  12:00:05 INFO  reserved stock order=101 offset=101        <- same record, second consumer
A  12:00:06 WARN  CommitFailedException: group has already rebalanced and assigned the partitions to another member

The fix: a guard table in the same transaction as the business change.

processed_messagesruns offline
# illustrative output
A: INSERT processed_messages(event_id='e-101') + reserve stock   -> committed
B: INSERT processed_messages(event_id='e-101')  -> duplicate key  -> skip, no second reservation   ✓

Going deeper One precision on the new protocol, as of Aug 2026: the broker side of KIP-848 is on by default in Kafka 4.0, but a consumer only uses it when its client is configured with group.protocol=consumer; the client default is still the classic protocol, so a group does not get the benefit until each consuming service opts in, and a group must be entirely on one protocol.

Two more mechanics worth knowing.

  • How long the classic pause can last: it is bounded by session.timeout.ms (45 seconds by default since 3.0) for a crashed member and by max.poll.interval.ms (5 minutes) for a slow one. A consumer that processes one slow record can freeze its group for minutes.
  • Static membership: group.instance.id set per pod lets a restarted pod rejoin with its old assignment inside the session timeout without triggering a rebalance at all. It is the cheapest fix for rebalance churn during rolling deploys.

Land it A rebalance redelivers whatever was uncommitted, so idempotent consumers are the requirement and the new protocol only makes the pause shorter.

Likely follow-ups
"A rolling deploy of ten pods causes ten rebalances. How do you reduce that?"

Three levers.

  1. Static membership: give each pod a stable group.instance.id, such as the pod's ordinal in a StatefulSet. When a pod restarts within the session timeout it picks up its old partitions and nobody else is disturbed. A rolling deploy then causes no rebalances if each pod is back within the timeout.
  2. Cooperative assignment: with the cooperative-sticky assignor or the KIP-848 protocol, a rebalance moves only the partitions that must move, so the other pods keep processing.
  3. Graceful shutdown: on termination the pod finishes its current batch, commits offsets, and calls close(). It leaves the group cleanly instead of being detected as dead after the session timeout. Spring Kafka does this on context shutdown if the pod's termination grace period is long enough.
rolling deploy of ten podsruns offline
# illustrative output
no levers:      10 restarts -> 10 rebalances x ~5 s pause each     ✗ ~50 s of stalled consumption
all three:      10 restarts ->  0 rebalances (pod back inside session.timeout.ms) ✓

With those three, a rolling deploy is nearly invisible to throughput. Without them it is ten pauses of several seconds each.

"What exactly happens to a message that a consumer was processing when the rebalance took its partition?"

In the classic protocol, the consumer is told to revoke its partitions at the next poll().

If it is mid-way through processing a batch, it does not find out until it returns to poll. It completes the work, including database commits.

When it then tries to commit the offset, it gets a CommitFailedException because it no longer owns the partition.

Meanwhile the new owner has started from the last committed offset, which is before that batch. It processes the same records again.

So the outcome is duplicate processing, not loss. The guard against it is the idempotent consumer.

In the cooperative protocols the window is smaller because only the moving partition is affected, but the same thing happens for that partition.

The practical rule is to keep each poll's processing short, commit soon after the work commits, and make every handler safe to run twice.

"How do you monitor rebalances and know when they have become a problem?"

The consumer exports metrics through Micrometer: the rebalance count, the rebalance latency, and the time since the last rebalance. Spring Kafka also logs partition assignment and revocation events. On the broker, the group coordinator's metrics show the group state.

What I graph is rebalances per hour per group and the p99 rebalance duration.

A healthy group rebalances only when it is deployed or scaled. A group rebalancing every few minutes with no deploys is in a loop. The cause is almost always a member exceeding max.poll.interval.ms and being kicked out.

I alert on more than a handful of rebalances an hour outside a deploy window. I correlate them with the lag graph, because a rebalance loop shows as lag that grows in steps.

The log line to search for is "member left group" with the reason, which names the timeout that fired.

rebalance loopruns offline
# illustrative output
12:00  rebalance #1  (member inv-3 exceeded max.poll.interval.ms)   lag 0 -> 40k
12:07  rebalance #2  (same member rejoined, same slow batch)         lag 40k -> 90k
12:14  rebalance #3  ...                                              lag grows in steps, no deploy in sight
"What does the new protocol change about the assignment logic — where does it run now?"

In the classic protocol, one of the consumers, the group leader, computes the assignment after all members have rejoined. That is why everyone has to stop and report in.

In KIP-848 the group coordinator on the broker holds the group's target assignment. It computes changes itself when a member joins or leaves.

It then tells each member individually, in its heartbeat response, which partitions to give up or take.

A member gives up only what it is told to and keeps processing everything else. There is no group-wide pause, and a member that is slow to respond delays only its own partitions.

The assignor logic, range and uniform, now runs server-side. Custom assignors written for the client side do not apply and have to be reconsidered.

For operators it means rebalance behaviour is visible and tunable from the broker, and for consumers it means a much smaller blast radius per change.

Q35. "At-most-once, at-least-once, exactly-once — what does Kafka really give you, and where does 'exactly-once' stop?"

Reveal answer

Strong answer The three terms describe what happens to a message across failures.

  • At-most-once: the consumer commits the offset before processing, so a crash mid-processing loses the message. No duplicates, possible loss.
  • At-least-once: the consumer processes and then commits, so a crash between the two redelivers. No loss, possible duplicates. This is the default and the one to design around.
  • Exactly-once in Kafka means a specific feature. A transactional producer (transactional.id set) can atomically write to several partitions and commit consumer offsets in the same transaction. Consumers with isolation.level=read_committed see only committed writes. That gives exactly-once for a read-from-Kafka, write-to-Kafka pipeline such as Kafka Streams.

It stops at the edge of Kafka. The moment a consumer writes to PostgreSQL, calls an HTTP API, or sends an email, that side effect is outside the Kafka transaction and can happen twice.

So for services the honest guarantee is at-least-once delivery plus an idempotent consumer.

That gives exactly-once effect. A guard table of processed event ids sits in the same database transaction as the business change, so a duplicate is detected and ignored.

Picture it One PaymentCompleted event consumed by the Order service, with a crash between the database commit and the offset commit, with and without a guard table (pattern: idempotent consumer).

The setup: the handler, with the guard in the same transaction as the business change.

PaymentCompletedHandlerruns offline
@Transactional
void on(PaymentCompleted e) {
    if (processedRepo.existsById(e.eventId())) return;   // ✅ FIX: duplicate detected, ignore
    processedRepo.save(new ProcessedMessage(e.eventId()));
    orders.markPaid(e.orderId());                         // same DB transaction
}   // ❌ TRAP without the guard: markPaid runs again on redelivery

The trace: a crash after the database commit and before the offset commit.

delivery traceruns offline
# illustrative output
Kafka offset 41 PaymentCompleted(o-881) -> Order consumer
  1  DB: processed_messages += e-77, orders o-881 = PAID, COMMIT          ✓
  2  consumer crashes before committing offset 41                        ✗
  3  restart: committed offset still 40 -> offset 41 delivered again
  4  guard: e-77 already in processed_messages -> skip                   ✓ exactly-once effect

What you see: the rows after the redelivery.

table stateruns offline
# illustrative output
                    no guard                    with guard
orders o-881        PAID (applied twice)        PAID (applied once)
processed_messages  (none)                      e-77
email sent          2 times                     1 time

Land it Kafka's exactly-once is real inside Kafka and a marketing phrase outside it, which is why the guard table is not optional.

Likely follow-ups
"Explain how the transactional producer commits offsets and writes atomically — what is the broker doing?"

The sequence:

  1. The producer begins a transaction with a transaction coordinator on the broker, identified by its transactional.id.
  2. Every write it makes to any partition is tagged with the transaction.
  3. The consumer offsets it wants to commit are sent as writes to the internal offsets topic through the same producer, inside the same transaction, using sendOffsetsToTransaction.
  4. On commit, the coordinator writes a prepare record to its transaction log, then writes a commit marker into every partition the transaction touched, then completes the log entry.
  5. A consumer with isolation.level=read_committed buffers messages from open transactions. It releases them only when it sees the commit marker, or discards them on an abort marker.
one transactionruns offline
# illustrative output
begin(txn-id=orders-p0)
  write  shipments-topic  p3  ShipmentRequested(o-881)      (tagged, invisible to read_committed)
  write  __consumer_offsets  group=ship  orders p0 offset 42  (tagged)
commit -> markers in shipments p3 and __consumer_offsets   ✓ output visible AND offset advanced together
abort  -> abort markers                                    ✓ neither

So "consume, process, produce, commit offsets" becomes one atomic unit. Either the output messages are visible and the input offsets are advanced, or neither.

The cost is latency per transaction, typically tens of milliseconds, and the coordinator as a dependency.

"What happens if the transactional producer crashes mid-transaction, and what is a zombie?"

The open transaction times out. transaction.timeout.ms is one minute by default. The coordinator aborts it, writing abort markers so read-committed consumers skip its writes.

When a new producer instance starts with the same transactional.id, its initialisation bumps an epoch at the coordinator. That also aborts any transaction still open from the previous instance.

A zombie is the old instance when it is not actually dead, for example a paused pod or a network partition. It comes back and tries to continue its transaction. The broker rejects its writes because its epoch is stale, so it cannot corrupt the log.

fencing by epochruns offline
# illustrative output
instance 1  transactional.id=ship-p0  epoch 4   pauses (GC / partition)
instance 2  transactional.id=ship-p0  initTransactions -> epoch 5, old txn aborted
instance 1  resumes, writes with epoch 4  -> rejected (ProducerFencedException)   ✓ zombie fenced
random id per start: instance 2 gets id ship-xyz epoch 0 -> instance 1 never fenced   ✗

That fencing is why the transactional id must be stable per logical producer, such as per partition or per task in Kafka Streams. A random id gets a fresh epoch each time and never fences the zombie.

It is one of the more subtle configuration mistakes and shows up as occasional duplicates that nobody can explain.

"Kafka Streams claims exactly-once end to end. Why does that not extend to a database write in a plain consumer?"

Because Kafka Streams stays inside Kafka. Its inputs, its outputs, its state-store changelogs, and its offsets are all Kafka topics. One Kafka transaction covers everything the application touched.

The moment a step writes to something that is not a Kafka partition, such as a PostgreSQL row or an HTTP call, that write cannot be enrolled in the Kafka transaction.

A crash between the external write and the transaction commit leaves the external effect done and the offset not committed. The record is processed again.

There is no two-phase commit between Kafka and a database in the standard client.

There are two ways to close that gap:

  • Idempotent side effect: the guard table in the same database transaction as the business write.
  • Route through a topic: write to a Kafka topic and let a connector such as the JDBC sink do the database write. That pushes the idempotency need into the connector, where it typically uses upserts keyed by primary key.
"Is at-most-once ever the right choice?"

Occasionally, for data where a gap costs less than a duplicate and where processing is expensive.

Examples:

  • High-frequency metrics or telemetry: losing one sample from thousands per second is invisible, and re-emitting one would distort a counter.
  • A notification that must not be sent twice under any circumstances, where not sending it is tolerable.
  • A cache-invalidation stream: a lost message is repaired by the time-to-live anyway.

The implementation is to commit the offset before processing, or to use auto-commit with processing that can be lost.

It is never right for anything with a business consequence, such as orders, payments or inventory.

It should be an explicit, documented choice per consumer with a reason. The default at-least-once plus idempotency covers most cases and does not lose data.

I mention it mainly so that a team choosing auto-commit understands they have chosen at-most-once.

Q36 · Scenario. "Consumer lag on the orders topic has grown from near zero to 4 million messages over three hours and is still climbing. Diagnose it in order."

Reveal answer

Strong answer Consumer lag is the gap between the latest offset on each partition and the consumer group's committed offset; growing lag means consumption is slower than production.

Evidence to collect, in order:

  1. Lag per partition: uniform growth means the consumer is slow. Growth on one partition means a hot key or a stuck consumer.
  2. Group membership: the consumer group's member count and recent rebalances.
  3. Processing time: the consumer's time per record.
  4. Producer rate: did production spike?

Causes ranked, each with its fix:

  1. Slow downstream inside the consumer: a database query that lost its index, or an HTTP call that started timing out, so each record takes 500 milliseconds instead of 5. Fix or bulkhead the slow dependency.
  2. Rebalance loop: processing exceeds max.poll.interval.ms, the member is kicked, rejoins, and repeats without committing. Raise max.poll.interval.ms or reduce max.poll.records to keep each poll short.
  3. Poison message: it fails and is retried forever, blocking its partition. Route failures to a dead-letter topic after N attempts.
  4. Real production spike that exceeds the group's capacity. Scale consumers up to the partition count, which is the ceiling.

Prevention is an alert on lag growth rate rather than absolute lag, and a partition count with headroom.

Picture it The lag of the Inventory consumer group on the orders topic, read per partition, for two different causes (related: dead-letter queue for the poison-message case).

What you see: the describe output when the consumer is slow, so every partition grows.

kafka-consumer-groups --describe (slow consumer)runs offline
# illustrative output
GROUP      TOPIC   PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG
inventory  orders  0          7,100,200       7,433,900       333,700
inventory  orders  1          7,099,800       7,433,100       333,300
inventory  orders  2          7,100,500       7,434,000       333,500     <- all partitions climb together

What you see: the same command when a poison message blocks one partition.

kafka-consumer-groups --describe (poison message)runs offline
# illustrative output
inventory  orders  0          7,433,800       7,433,900       100
inventory  orders  1          7,100,000       7,433,100       333,100     <- stuck at one offset, others healthy
inventory  orders  2          7,433,950       7,434,000       50

Make the invisible visible: from symptom to cause to action.

Lag diagnosis
SymptomRoot causeAction
All partitions grow evenlySlow downstream: processing time per record went from 5 ms to 500 msFix or bulkhead the dependency
Lag grows in steps, many rebalancesPoll exceeds max.poll.interval.ms, member kicked and rejoinsShorten each poll with max.poll.records or raise the interval
One partition stuck at one offsetPoison message retried foreverBounded retry, then dead-letter topic
Production rate doubled, processing time normalArrival rate above group capacityScale consumers up to the partition count

Land it Lag is a symptom with four common causes, and per-partition lag plus the rebalance count separate them in a minute.

Likely follow-ups
"You fixed the slow dependency and lag is still climbing. What next?"

Then either the fix has not reached the consumer's actual bottleneck or the arrival rate is now above the group's ceiling.

I would measure the consumer's per-record processing time directly and compare it with the per-partition arrival rate. Spring Kafka exposes listener timings through Micrometer.

If processing is fast again but lag still grows uniformly, the group simply has fewer active members than it needs. Two checks:

  • Stuck members: members that are assigned partitions but not polling, which happens when a thread is stuck.
  • Partition count: with 12 partitions and 12 consumers, adding a thirteenth does nothing.

If lag grows on one partition only, a hot key is sending most traffic to one partition, such as a single big customer or a null key. The fix is the key choice or a parallel consumer within the partition.

And I would confirm the producer rate has not changed, because a backfill job upstream can double the arrival rate quietly.

capacity checkruns offline
# illustrative output
arrival 4,000 rec/s ; per-record time 2 ms -> one thread does 500 rec/s -> 12 partitions x 500 = 6,000 rec/s   ✓ enough
backfill doubles arrival to 8,000 rec/s -> ceiling 6,000 rec/s -> lag grows 2,000 rec/s                       ✗
"How do you catch up 4 million messages without causing the next incident?"

Carefully, because a consumer draining at full speed hits its downstream at full speed.

  1. Estimate the drain time. At a healthy 2,000 records a second per instance with six instances, 4 million takes about six minutes, which is fine. At 200 a second it is an hour, and I would scale up to the partition count for the duration.
  2. Check what the consumer writes to, a database or another service, and whether it can absorb the burst. If not, I rate-limit the consumer, which Spring Kafka allows through a pause-and-resume on the container, or I reduce max.poll.records so each poll is smaller.
  3. Watch the lag graph's slope, not just its value. It should be falling steadily. A flattening means the downstream is saturated.
drain time arithmeticruns offline
4,000,000 / (6 instances x 2,000 rec/s) = 4,000,000 / 12,000 = ~333 s  (about 6 min, as long as production is idle)
4,000,000 / (6 instances x   200 rec/s) = 4,000,000 /  1,200 = ~3,333 s (about 56 min)

If the backlog contains work that is now stale — a search-index update superseded by a later one for the same key — I might skip ahead by resetting offsets, but only with a clear reconciliation plan.

"What alert would have fired earlier, and how do you avoid it being noisy?"

An alert on lag growth rate, rather than on absolute lag. The rule is lag now minus lag ten minutes ago, sustained for two windows. Absolute thresholds are either too high for a quiet topic or too low for a busy one.

A more meaningful form is time lag: the age of the oldest unconsumed record. Kafka's consumer metrics or Burrow can derive it from record timestamps, expressed as "the consumer is 40 minutes behind".

A threshold in seconds is easy to reason about. The business tolerates two minutes of delay on order events, and the threshold stays valid as traffic grows.

To avoid noise, I add two conditions:

  • the group has at least one active member, because lag on a deliberately stopped consumer is expected;
  • the condition holds for ten minutes, so a brief spike after a deploy does not page anyone.

The page should link to the per-partition lag dashboard so the first diagnostic step is one click.

"What is a poison message in practice and how do you find it in 4 million?"

A poison message is one the consumer cannot process no matter how many times it tries. Examples are a malformed payload, a reference to an entity that does not exist, or a value that triggers a bug.

If the error handler retries it forever, that partition stops and every message behind it waits. Other partitions continue, so the lag graph shows one partition climbing.

Finding it is quick because it is at the front of the queue. The consumer's log shows the same offset failing repeatedly, and the exception names the reason.

consumer logruns offline
# illustrative output
12:00:01 ERROR orders-1@7100000  JsonParseException: Unexpected character ('}')  attempt 1
12:00:02 ERROR orders-1@7100000  JsonParseException: Unexpected character ('}')  attempt 2
12:00:03 ERROR orders-1@7100000  JsonParseException: Unexpected character ('}')  attempt 3   <- same offset, same exception

The tools are kafka-console-consumer with the partition and offset, or a small admin endpoint that reads one record by offset.

The fix is a bounded retry — Spring Kafka's DefaultErrorHandler with a backoff of a few attempts — after which the record goes to the dead-letter topic and the partition moves on, and the alert is on the dead-letter topic rather than on the stuck partition.

Q37. "What is a dead-letter topic, when does a message go there, and what do you do with it afterwards?"

Reveal answer

Strong answer A dead-letter topic (or queue) is where a consumer sends a message it has failed to process after a bounded number of attempts. The message stops blocking the partition and is preserved for inspection.

The trigger should distinguish two kinds of failure:

  • Transient (a timeout, a database deadlock): retried in place with backoff, a few times. Spring Kafka's DefaultErrorHandler with a DeadLetterPublishingRecoverer does exactly this. It retries N times, then publishes the record to topic.DLT with headers recording the exception and original partition.
  • Permanent (a payload that cannot be parsed, a validation error, a reference to an entity that does not exist): goes to the dead-letter topic on the first attempt, because retrying a poison message only delays everything behind it.

Afterwards, the dead-letter topic must have an owner and a process:

  • an alert on its growth;
  • a dashboard;
  • a tool to inspect and re-drive messages back to the source topic after the bug is fixed;
  • a retention long enough to survive a weekend.

The commonest failure is a dead-letter topic that nobody reads, which is a silent data-loss mechanism with a reassuring name.

Picture it One bad OrderPlaced record on the orders topic, retried and then moved to orders.DLT so Inventory keeps moving (pattern: dead-letter queue).

The setup: bounded retry for transient errors, immediate dead-lettering for permanent ones.

Kafka error handlingruns offline
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
    var recoverer = new DeadLetterPublishingRecoverer(template);          // publishes to orders.DLT
    var handler = new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3)); // 3 retries, 1 s apart
    handler.addNotRetryableExceptions(JsonParseException.class,          // ✅ permanent: DLT at once
                                      ValidationException.class);
    return handler;                                                       // ❌ TRAP without it: partition blocked forever
}

The trace: partition 1, offset 7,100,000 is malformed.

partition traceruns offline
# illustrative output
orders-1@7100000  JsonParseException    permanent -> publish to orders.DLT, commit, move on      ✓
orders-1@7100001  processed normally                                                              ✓
orders-1@7100010  SQLTransientConnectionException (timeout)  transient -> retry 1 s, 1 s, 1 s, then DLT   ✓

What you see: the dead-lettered record and what the headers tell the owner.

orders.DLT record headersruns offline
# illustrative output
key=order-123  value=<original bytes, unchanged>
kafka_dlt-original-topic=orders
kafka_dlt-original-partition=1
kafka_dlt-original-offset=7100000
kafka_dlt-exception-fqcn=com.fasterxml.jackson.core.JsonParseException

Land it The dead-letter topic is only a safety net if someone is assigned to empty it; otherwise it is a place messages go to be forgotten.

Likely follow-ups
"What does a message in the dead-letter topic need to carry so someone can act on it later?"

Enough to answer three questions: where did it come from, why did it fail, and how do I put it back.

Spring Kafka's DeadLetterPublishingRecoverer adds headers for the original topic, partition, offset and timestamp, the exception class and message, and the stack trace. It keeps the original key and payload untouched.

I add the consumer group name and the application version. A failure caused by a bug in version 4.2 can then be replayed only after 4.3 is deployed.

The payload is preserved exactly, with no transformation. Re-driving it means producing the same bytes back to the source topic with the same key. That keeps ordering relative to later messages for that key as close as possible.

The headers also let a dashboard group failures by exception type. It shows whether one bug produced a thousand dead letters or a thousand different problems exist.

dead letters grouped by exceptionruns offline
# illustrative output
count  exception                      app-version
 998   JsonParseException             4.2      -> one bug, fix and re-drive after 4.3
   2   ValidationException            4.2
"How do you re-drive dead letters without breaking ordering for the keys involved?"

Honestly, ordering is already broken for those keys. Later messages for the same key have been processed while the failed one sat in the dead-letter topic. Re-driving puts the old message after newer ones.

re-drive after newer eventsruns offline
# illustrative output
orders-1@100 OrderUpdated(123, v=1)  -> DLT (bug)
orders-1@101 OrderUpdated(123, v=2)  -> applied, order 123 at v=2
re-drive v=1 -> handler sees current v=2 > 1 -> ignore                 ✓ order-tolerant
              without the version check: order 123 goes back to v=1   ✗

So the re-drive tool has to be paired with a consumer that copes. It is an idempotent, order-tolerant handler. It checks the entity's current version before applying an update, using a version or sequence in the event, and ignores an update older than what it has already applied.

For a re-drive after a bug fix, I re-drive in original order, by original offset, for each key. That restores the relative order among the dead letters themselves.

Where strict ordering matters and the consumer cannot be made tolerant, the alternative is to stop the consumer on the first permanent failure for a key rather than dead-lettering it. The price is a stuck partition. That is rare; most consumers can be made tolerant.

"Distinguishing transient from permanent — how does the code know?"

By exception type, declared explicitly. Spring Kafka's error handler takes a list of exceptions to treat as not retryable, through addNotRetryableExceptions. Everything else is retried with the configured backoff.

Exception classification
FailureClassOutcome
Deserialisation error, validation error, my own "entity not found after reconciliation"Not retryableDead-letter topic at once
Timeout, connection error, deadlock, optimistic-lock conflictRetryableBackoff, then dead-letter topic after the attempts
Unknown exceptionRetryable, low attempt countA bug does not block a partition for long

Deserialisation is a special case because it happens before the listener runs. The ErrorHandlingDeserializer wraps the failure so the record reaches the error handler rather than crashing the poll loop.

The classification is tested: a unit test that throws each type and asserts whether the record was retried or dead-lettered.

"What is the retention on the dead-letter topic and what happens to a message nobody looks at?"

The retention has to be longer than the time it will realistically take someone to notice and act, including a holiday weekend. I set it to at least two weeks and often thirty days, which is cheap because the volume is small.

A message nobody looks at within retention is deleted by the broker, silently, and the data it represented is lost. That is the failure mode of a dead-letter topic without an owner.

To make that impossible to ignore:

  • the alert fires on the first message, not on a threshold, and the on-call runbook says what to do;
  • a weekly report lists the topic's oldest message age and count, so a growing pile is visible to the team lead.
retention versus attentionruns offline
# illustrative output
retention 7 days, nobody reads, message arrives Friday 18:00
Fri 18:00 DLT += 1      Sat Sun ...      next Fri 18:00  segment deleted   ✗ silent data loss
with alert on first message:  Fri 18:01 page -> owner triages -> re-drive or discard   ✓

For a business-critical stream, I add a second safety: the dead-letter consumer writes each record into a database table with a status, so retention no longer matters and the queue becomes a work list with a state.

Q38 · Design. "Design how event schemas evolve across twenty consumers without breaking any of them. Include the registry, the compatibility mode, and the rule for consumers."

Reveal answer

Strong answer Requirements: producers must be able to add information over time; consumers must keep working on both old and new events, because a topic holds days of history in mixed versions.

Design, part one: events are serialised with a schema — Avro or Protocol Buffers rather than free-form JSON.

Design, part two: every schema version is registered in a schema registry (Confluent's, Apicurio, or the cloud equivalent) that assigns an id embedded in each message.

The producer registers a new version before producing; the registry rejects it unless it passes the configured compatibility check.

I set the mode to backward-transitive: a consumer using the newest schema can read every older version.

  • Permitted: adding optional fields with defaults, and removing fields.
  • Forbidden: renaming a field, changing a type, or adding a required field.

Consumer rule: be a tolerant reader. Three habits:

  1. Unknown fields: ignore them.
  2. Unknown enum values: never fail on one.
  3. Schema choice: read from the schema id in the message, not a hard-coded version.

For a genuinely breaking change, publish to a new topic (orders.v2), run both for a migration window, and move consumers one at a time.

The trade-off is ceremony: every event change goes through the registry check in CI.

What I would not do is use JSON with no schema and rely on code review to keep twenty consumers safe.

Picture it one topic holding two schema versions at once, two consumers reading it, and the registry refusing an unsafe change on the running order example.

The setup: the OrderCreated schema at version 1 and a compatible version 2 that adds a field with a default.

OrderCreated schema, v1 and v2runs offline
// v1 (registry id 7)
{"type":"record","name":"OrderCreated","fields":[
  {"name":"orderId","type":"string"},
  {"name":"total","type":"long"}]}

// v2 (registry id 8): ✅ compatible, new field has a default
{"type":"record","name":"OrderCreated","fields":[
  {"name":"orderId","type":"string"},
  {"name":"total","type":"long"},
  {"name":"currency","type":"string","default":"EUR"}]}

// v3 attempt: ❌ TRAP: rename total -> amount, no default, no alias
// Result: the registry refuses to register it (HTTP 409, incompatible)

Make the invisible visible: the topic is a mix of both versions, and each consumer decodes with the writer schema named by the id in the message.

topic with mixed versionsruns offline
# illustrative output
orders  partition 0
offset  schema id  fields in the bytes
  100     7        orderId=A1 total=340
  101     7        orderId=A2 total=95
  102     8        orderId=A3 total=120 currency=USD
  103     8        orderId=A4 total=60  currency=EUR

consumer billing  (reader = v2, deployed)
  off 100  writer v1 -> currency missing -> default "EUR"   ✓
  off 102  writer v2 -> currency = USD                      ✓
consumer audit    (reader = v1, not upgraded yet)
  off 102  writer v2 -> unknown field currency skipped      ✓
consumer audit, hard-coded v1 parser on raw JSON
  off 102  unexpected field -> exception, partition stuck   ✗

Why: the registry check happens once, at registration time, so an incompatible schema never reaches the topic; the schema id lets every consumer decode any version it meets.

Land it Compatibility enforced by a registry in the pipeline is what turns twenty consumers from a coordination problem into an ordinary deploy.

Likely follow-ups
"Backward, forward, full — which mode exactly, and why not full-transitive?"

Backward compatibility means a consumer using the new schema can read data written with the old one; forward means a consumer using the old schema can read data written with the new one; full means both.

Transitive means the check is against every earlier version, not just the previous one.

For events, where consumers upgrade at their own pace and a topic holds a mix, I want consumers on the newest schema to read everything older, which is backward-transitive; and I also want a consumer that has not upgraded to keep reading new events, which is forward compatibility.

Full-transitive gives both, and it is what I would choose for a topic with twenty consumers if the producer team accepts its restrictions: only optional fields with defaults may be added or removed.

The reason teams pick backward only is that it also allows removing a required field, which forward forbids; for a widely consumed topic that flexibility is not worth the risk of breaking a lagging consumer.

"How does the consumer get the schema for a message it has never seen?"

Each message carries a small header — in the Confluent wire format, a magic byte and a four-byte schema id — instead of the schema itself.

The consumer's deserialiser reads the id, looks it up in the registry over HTTP, caches it, and decodes the payload with that writer schema, then resolves it against its own reader schema: Avro's resolution fills defaults for fields the reader has that the writer did not write, and skips fields the writer wrote that the reader does not know.

So a consumer built against version 3 can read a message written with version 5, provided the changes were compatible.

The registry is therefore a runtime dependency on first sight of each schema id, which is a handful of calls per consumer lifetime, and a cached one thereafter; I make the cache persistent across restarts or pre-warm it, because a registry outage during a mass restart would otherwise stop every consumer.

"A breaking change is unavoidable — a field's type must change. Walk me through the migration across twenty consumers."

I never change the field in place. Step one: add a new field with the new type alongside the old, populated by the producer with both values, which is a compatible change; deploy the producer.

field type migration, step by stepruns offline
# illustrative output: changing "total" from int to long-with-currency
step  producer writes             schema check     consumers
 1    total(old) + totalMoney(new)  compatible ✓    keep reading total
 2    same                          -              move to totalMoney one by one
 3    totalMoney only               compatible ✓    all on totalMoney (metric = 20/20)
 4    remove total                  compatible ✓    none read it
(in-place type change)              incompatible ✗  registry rejects the schema

Step two: each consumer moves to the new field on its own schedule; I track adoption by a metric on the consumer side or by asking the registry which schema versions consumers have fetched.

Step three: when every consumer reads the new field, the producer stops populating the old one, which is still compatible if it had a default. Step four: remove the old field, which is compatible under backward rules.

If the change cannot be expressed as add-then-remove — a whole event's meaning changes — I create orders.v2, dual-publish to both topics for a migration window, move consumers one by one, and retire v1 when its consumer groups are gone, which the broker's group list shows.

The whole thing takes weeks, and that is the intended cost of a breaking change.

"Under time pressure, what would you cut from this design and what is the minimum?"

The minimum is a schema, a registry with a compatibility check, and a tolerant reader, and I would not cut any of the three.

What I would cut first is the CI integration: registering the schema from the pipeline with a pre-check is nice, but the registry's own rejection at registration time is the real guard, so for a first release the producer can register at startup and fail to start if incompatible.

I would also defer the dual-topic procedure for breaking changes and simply forbid breaking changes for now. And I would start with backward compatibility rather than full-transitive if the producer team needs the flexibility to ship, tightening later.

What I would not do is start with free-form JSON with the intention of adding a schema later, because by the time it matters there are twenty consumers each parsing the JSON their own way and no way to know what would break.

Q39. "Event notification, event-carried state transfer, event sourcing — three different things. Explain each and say which the order system should use."

Reveal answer

Strong answer An event notification says only that something happened and carries an id: "order 123 was created". Consumers who need details call back to the owner.

It is small and loosely coupled, but it turns every event into a synchronous call, and a burst of events becomes a burst of calls on the owner.

Event-carried state transfer puts the relevant data in the event — "order 123 was created for customer 9, three items, total 340".

Consumers use it to build their own local copy and never call back.

Its costs:

  • Bigger messages.
  • An eventually consistent copy in every consumer.

What it buys is real independence for consumers.

Event sourcing is a different level entirely: the service's own state is not stored as current rows but as the full sequence of events, and the current state is rebuilt by replaying them.

It gives a perfect audit trail and time travel. What it costs:

  • Snapshots for performance.
  • Versioning of every historical event forever.
  • Projections for reads.

For the order system I would use event-carried state transfer for the events other services consume, keep a conventional relational model inside each service, and use event sourcing nowhere unless a domain — a ledger, an audit-critical workflow — specifically needs its history as the source of truth.

Picture it the same order 123 shown as three different things: a notification, a state-carrying event, and an event-sourced history (see Pattern: Event Sourcing).

Make the invisible visible: what travels on the topic, and what each service stores afterwards.

three styles for order 123runs offline
# illustrative output
1) Event notification   topic orders, offset 501
   {"type":"OrderCreated","orderId":123}
   payment then calls GET /orders/123          <- one call per event
   burst of 200 events -> 200 calls on order service

2) Event-carried state transfer   offset 501
   {"type":"OrderCreated","orderId":123,"customerId":9,
    "items":[{"sku":"S1","qty":2,"price":100},...],"total":340}
   payment.order_copy: (123, 9, 340, "CREATED")   <- no call back

3) Event sourcing   order service's own table "order_events"
   order_id  seq  type
   123        1   OrderCreated   total=340
   123        2   OrderPaid
   123        3   ItemRemoved    sku=S2
   current state = replay seq 1..3 (no "orders" row is the truth)

Why: style 1 keeps messages tiny but makes every event a synchronous call; style 2 removes the call at the price of a copy; style 3 changes how the owner itself stores state, so it is a separate decision from how events are published.

Land it Carry state in events so consumers can stand alone, and reserve event sourcing for domains that are about history rather than merely producing it.

Likely follow-ups
"With event-carried state, how much of the order do you put in the event? Everything?"

Enough for the known consumers to act without calling back, and no more than the owner is prepared to keep stable.

For OrderCreated that is typically the order id, customer id, the line items with product ids, quantities, and unit prices, the totals, currency, and the shipping address, because payment, inventory, and shipping each need a subset of those.

What I leave out are internal fields — the version, the last-modified user — and anything that is really another service's data, such as the customer's name, which consumers should get from the customer events. A payload of a few kilobytes is fine.

The event schema is a public contract, so every field I include is one I must keep compatible, which is the argument against dumping the whole entity.

When a consumer needs something not in the event, I add it as a compatible change rather than have them call back, because the call-back path reintroduces the synchronous dependency.

"A consumer's local copy drifts from the owner. How do you detect and repair that?"

Drift happens when an event was lost before the outbox existed, when a consumer had a bug, or when a dead letter was never re-driven.

reconciliation mismatchruns offline
# illustrative output: nightly job, payment.order_copy vs order service
order_id  owner version  copy version  verdict
  120          4              4         ✓
  121          3              3         ✓
  122          5              4         ✗ copy is behind (event 5 lost / in DLQ)
mismatches: 1 of 3 sampled  -> alert, fetch order 122 and overwrite

Detection is a reconciliation job: periodically, the consumer compares a sample or the full set of its copied rows with the owner, either by calling a bulk endpoint that returns ids and versions or by reading a compacted snapshot topic the owner publishes, and counts mismatches.

Repair for small drift is to fetch the differing entities from the owner and overwrite; for large drift, a full rebuild from a snapshot.

To make this cheap the owner exposes a version or updated-at per entity, so the comparison is on small values rather than whole records.

I run the reconciliation nightly and alert on any mismatch count above a handful, because drift compounds: a copy that is 0.1% wrong today is the copy support will find wrong in a ticket next month.

"Is there a middle ground between notification and full state transfer?"

Yes, and it is often the right compromise: an event that carries the identifiers and the small set of fields most consumers need, plus a version number, with a bulk endpoint on the owner for consumers that need more.

The version number is the key part, because it lets a consumer that does call back know whether the state it fetched matches the event it is processing, or is already newer.

This keeps events small and contracts narrow while avoiding the burst-of-calls problem for the common consumers.

The other middle ground is a snapshot topic: the owner publishes the full current state per entity to a compacted topic, and the change events stay small; a consumer that needs the whole entity reads the snapshot topic into a local copy and uses the change events as triggers.

That splits the two concerns — notification of change and transfer of state — into two streams.

Q40 · Scenario. "A team implemented request-reply over Kafka: the API publishes a command, blocks waiting for a reply on a reply topic, and times out after 3 seconds. p99 latency is 2.8 seconds and 4% of requests time out. What would you tell them?"

Reveal answer

Strong answer They have built a synchronous call out of asynchronous parts and paid for both.

The symptom is a p99 near the timeout and a steady timeout rate. It says the reply path's latency is dominated by broker mechanics rather than work.

  • Producer batching: linger.ms holds each message.
  • Consumer poll intervals: a command waits for the worker's next poll.
  • Reply partition assignment: the reply consumer's own assignment adds more.

Each adds tens to hundreds of milliseconds, and any rebalance multiplies all of it.

The evidence: a trace of one request showing where the 2.8 seconds go, and the consumer lag on both topics.

The diagnosis is the pattern itself, not a tuning problem. The fix depends on what the caller actually needs.

If it needs an answer to continue, make the call synchronous — REST or gRPC with a timeout, breaker, and bulkhead — and stop routing it through the log.

If it does not, make the API return 202 Accepted with a request id, let the work complete asynchronously, and give the client a status endpoint or a webhook.

Prevention is a review rule: a broker is for decoupling in time; if a thread is blocked waiting on a reply, there was no decoupling and the broker is only adding latency and failure modes.

Picture it two requests through the command and reply topics, one healthy and one hit by a rebalance, with the API timing out at 3 seconds.

Make the invisible visible: one lane per component, with the time each stage adds.

request-reply over Kafkaruns offline
# illustrative output (ms since the API produced the command)
request R1 (normal)
  API         0   produce cmd (linger 50)            ✓
  cmd topic  50   offset 9001 written
  Worker    210   poll returns 500 records, R1 is #37 (37 x 10 ms ahead) 
  Worker    580   reply produced (linger 50)
  reply tpc 630   offset 7742
  API       740   reply consumer polls, matches id   ✓  total 740 ms

request R2 (reply consumer group rebalances)
  API         0   produce cmd
  Worker    600   reply produced
  API      2900   rebalance ends, reply consumer resumes   ✓ 2.9 s, p99 territory
request R3
  API      3000   timeout, client gets 504               ✗
  Worker   3100   finishes the work anyway, reply is dropped

The fix: the API returns 202 with an id and a status row the client reads; no thread waits on the log.

status table, 202 Acceptedruns offline
# illustrative output
POST /orders/123/pay            -> 202 Accepted  Location: /orders/123/status
request_status                  id   state        updated
  after POST                    r-9  PROCESSING   10:00:00
  after worker commits          r-9  DONE         10:00:01
GET /orders/123/status          -> {"state":"DONE"}

Land it Sync-over-async has the latency of a queue and the coupling of a call, and the cure is to pick one honestly.

Likely follow-ups
"They cannot change the API contract — the client expects a synchronous answer. What is the least invasive fix?"

Replace the broker hop with a direct call and keep the API exactly as it is.

The API service calls the worker service over REST or gRPC with a timeout, breaker, and bulkhead, and the worker does the same work it did when it consumed the command.

Nothing about the client changes, and the p99 drops from 2.8 seconds to whatever the work itself takes, typically tens of milliseconds.

If the worker also needs to be driven by the topic for other reasons, it can keep the consumer for those callers and expose the endpoint for this one.

What I would not do is tune the broker path — lower linger.ms, more reply partitions — because it might get the p99 down to a second and would still have every failure mode of the current design.

The one honest exception is when the worker is genuinely slow — seconds of work — and then the fix is an asynchronous API with a status endpoint, which does change the contract.

"Where does the 2.8 seconds actually go, concretely?"

Adding up the defaults explains it. Producer batching holds a message for up to linger.ms, which teams set to 20 to 100 milliseconds for throughput.

The worker's consumer polls on an interval and may be mid-way through a batch of records for other requests, so a command waits behind them; with max.poll.records at 500 and 10 milliseconds each, that is up to 5 seconds in the worst case.

The reply goes through the same batching and the reply consumer's own poll loop. Any rebalance on either side adds seconds, and with a consumer group per API instance, every API deploy causes one. Under load, consumer lag on either topic adds directly to latency.

So the p50 might be 150 milliseconds and look acceptable, while the p99 is the sum of the worst cases of each stage. A trace with spans at produce, consume, process, and reply shows which stage dominates, but the shape is inherent to the pattern.

"When is request-reply over a broker actually appropriate?"

When the caller genuinely benefits from the broker's properties and can tolerate its latency: when the worker is not reachable by direct call — behind a firewall, or a fleet of devices that connect outward only; when the work is long enough that seconds of overhead do not matter and the caller wants durability of the request; or when the pattern is used for a small number of administrative operations rather than the hot path.

RabbitMQ's direct-reply-to feature and Spring Kafka's ReplyingKafkaTemplate exist for these cases. Even then I would give the caller a timeout that reflects the broker's latency and a status endpoint as the fallback for a lost reply.

For a user-facing API with a 3-second timeout and thousands of requests a minute, none of those conditions hold, and the direct call wins.

"The team says they did it this way so the API stays up when the worker is down. Does it?"

No. When the worker is down, the command sits on the topic and the API blocks until its 3-second timeout, then returns an error, which is what a direct call with a 3-second timeout would have done, except the direct call would have failed faster on connection refused and its breaker would have opened.

The only difference is that the commands are preserved on the topic and the worker processes them when it returns, by which time the clients have received errors and, possibly, retried, so the worker does the work twice.

worker down: what the client seesruns offline
# illustrative output: worker down 5 minutes, API retries on timeout
10:00:00  API cmd c-1 (client attempt 1) -> topic   10:00:03 timeout, 504
10:00:05  API cmd c-2 (client retry)     -> topic   10:00:08 timeout, 504
10:05:00  worker returns: processes c-1 ✓, then c-2 ✓   <- same work twice, nobody waiting

So the API is not more available; it is equally unavailable with more latency and a backlog of stale work.

The version that would actually stay up is the asynchronous API: accept the request, return 202 with an id, and let the worker catch up; the client checks status later. That is a real gain from the broker, but it requires changing what the API promises.

08 · DrillData Consistency, Sagas, Outbox & Events — Q41–Q80

This is the section where service architectures are really tested, because the monolith's one transaction is gone and every guarantee has to be rebuilt by hand. The forty questions cover data ownership and the joins you lost, sagas and the states they pass through, the outbox and change data capture, idempotent consumers, and the read models built from events. Several are on-call scenarios — a saga stuck half-way, duplicate orders after a rebalance — and the answers walk them in diagnosis order.

Drill · Data ownership and consistency

These questions test whether you can explain what the split database costs, how to get data across a boundary without breaking it, and when the rule should bend.

Q41. "Why does each service need its own database? What is actually wrong with two services sharing one?"

Reveal answer

Strong answer A shared database is a hidden API. The moment two services read the same table, its columns, types, and meanings become a contract between them.

It is a contract with no version, no documentation, and no test. Neither service can change the schema without risking the other, and you are back to coordinated deploys.

It also couples them in two more ways:

  • At runtime: one service's long transaction or missing index slows the other's queries, and a lock held by one blocks the other.
  • In ownership: nobody can say which service owns "order status" when three of them update it.

Database-per-service makes one service the owner of each piece of data and forces everyone else through its API or its events, which are versioned, tested, and visible. The price is the one everyone feels: there is no transaction across services, and no JOIN across them either.

Queries that used to be a JOIN become an API call, a local copy maintained from events, or a read model built for that screen.

The rule has a sensible weaker form for small platforms — one database server, one schema per service, separate credentials so the wall is enforced by permissions — which keeps the ownership rule and gives up only failure isolation.

Picture it one shared table touched by three services, the rename that breaks one of them, and the same data after each service gets its own schema (Pattern: Database per Service).

The setup: the orders team renames a column in the shared database.

shared table, before and after the renameruns offline
# illustrative output
table orders (shared)                     writers/readers
id   status      total                    orders svc (writes), payments svc (writes status),
123  CREATED     340                      shipping svc (reads), report job (reads)

orders team deploys:  ALTER TABLE orders RENAME COLUMN status TO state;
table orders
id   state       total
123  CREATED     340

What you see: the other services find out in production.

payments service logruns offline
# illustrative output
payments  ERROR  UPDATE orders SET status='PAID' WHERE id=123
ERROR:  column "status" does not exist
shipping  ERROR  same message          report job  ERROR  same message

The fix: each service owns a schema and role; others go through the API or events.

what you see nowruns offline
# illustrative output
payments> SELECT * FROM orders.orders;
ERROR:  permission denied for schema orders
payments> -- must ask the order service: GET /orders/123  (versioned contract)

Land it The rule is about ownership, not hardware: one writer per table, and everyone else through a contract that can be versioned.

Likely follow-ups
"Show me how the weaker form is actually enforced in PostgreSQL."

One database, one schema per service, one role per service, and grants that make cross-schema access impossible rather than discouraged.

Concretely: CREATE SCHEMA orders AUTHORIZATION orders_svc, and for every other service role, no USAGE grant on that schema, so SELECT * FROM orders.orders from the payments role fails with a permission error.

I also revoke the default PUBLIC privileges on the public schema so nothing lands there by accident, and I make the schema owner the only role that can run migrations. Each service's connection string uses its own role and sets search_path to its schema.

The check that this holds is a nightly query over information_schema.role_table_grants that fails if any role has privileges on another service's schema. Foreign keys across schemas are forbidden by convention and detected by the same job. The result is a shared server with real walls.

"What is the runtime coupling, exactly — how does one service's query hurt another on a shared database?"

Three mechanisms. Locks: a long transaction in the analytics-style query holds a share lock that blocks a schema migration in the other service, and the migration's exclusive lock request then blocks every subsequent query on that table — a small report can freeze another team's service.

lock queue on a shared tableruns offline
# illustrative output
time  analytics-style query          migration (orders team)        other queries on table
 t0   SELECT ... (open 2 h)          -                              run ✓
 t1   still running                  ALTER TABLE ... waits for lock  run ✓
 t2   still running                  waiting (exclusive requested)   queue behind migration ✗
 t3   finishes                       gets lock, runs, releases       resume

Resources: CPU, I/O, and the shared buffer cache are one pool, so a badly indexed query from one service evicts the other's hot pages and slows its queries even without any lock.

And connections: max_connections is shared, so one service's pool that grows under load can starve the other of connections entirely. In PostgreSQL specifically, a long-running transaction anywhere in the database holds back vacuum for every table, so one service's forgotten open transaction bloats the other's tables.

These are the reasons "one server, many schemas" gives up failure isolation, and why I would move a service to its own instance the first time its neighbour's incident becomes its own.

"How would you find hidden cross-service table access in an existing shared database?"

From the database, not the code, because the code lies by omission.

In PostgreSQL I enable pg_stat_statements and, for a week, collect every distinct query with the role that ran it; a query from the payments role that names a table in the orders schema is a hit.

If services share a role, I first give each its own, which is a connection-string change. For a fuller picture I turn on statement logging with the application name set per service — application_name in the connection properties — and parse the log.

The output is a matrix of service against table, and every cell that is not the owner is either a read to move behind an API or event, or a write that is a real bug.

I have never done this exercise without finding at least one surprise: a report, an admin tool, or a cron job that nobody had listed as a consumer.

"Is a shared database ever the right final design?"

Only when the services sharing it are really one service, and then the right final design is to merge them.

There is one honest exception: a reporting or analytics database that many services feed and none owns, because it is a derived copy — a warehouse — and the services' own databases remain the source of truth.

That is not shared ownership; it is a read model fed by events or change data capture.

Another apparent exception, two services with strict transactional consistency needs, is really a merge case in disguise: if payment and ledger must always commit together, they should be one service with two modules, not two services holding hands through a database.

Where I have seen a shared database survive as a "final" design, it survived because nobody had the budget to fix it, and every team that touched it paid for that in coordinated deploys.

Q42. "You lost the JOIN. What are the three ways to get 'orders with customer name' across two services, and how do you choose?"

Reveal answer

Strong answer First, API composition: the caller fetches the orders, collects the customer ids, and calls the customer service once with the batch to fetch names, then joins in memory.

It is simple and always current, and it costs a synchronous dependency and a latency hop; it is the right choice for low-volume screens and for data that must be fresh.

Second, a local copy: the order service subscribes to "CustomerChanged" events and keeps the few customer fields it needs — name, tier — in its own table next to the orders.

Queries are local and fast, there is no runtime dependency, and the copy lags by the event delay; it is right for the fields an order needs constantly.

Third, a dedicated read model (the CQRS shape): a separate component consumes both order and customer events and maintains a denormalised table or search index shaped exactly for the screen.

It is the fastest for reads and the best for search and reporting, and it costs another component, another lag, and a rebuild story.

I choose by three questions:

  1. Freshness: how fresh must the data be?
  2. Read rate: how often is the screen read?
  3. Shape: is it simple (copy) or a cross-cutting view (read model)?

The one option I rule out is reading the customer service's tables directly.

Picture it the three replacements for "orders JOIN customers" on the same two tables, with the rows each option holds (the read model is the CQRS shape).

Make the invisible visible: the monolith JOIN is gone because the rows now live in two databases.

rows in each service, then the three pathsruns offline
# illustrative output
orders DB (order service)          customers DB (customer service)
 id   customer_id  total            id   name      tier
 123       9        340              9   Asha R.   GOLD
 124       9         95             11   Ben K.    BASIC

1) API composition   (nothing stored)
   order svc: SELECT ... -> [123,124]; ids = {9}
   GET /customers?ids=9  -> {9:"Asha R."}; join in memory     (1 extra call)

2) Local copy        orders DB gets  customer_copy
   customer_id  name      tier    <- fed by CustomerChanged events
        9       Asha R.   GOLD
   SELECT o.id, c.name FROM orders o JOIN customer_copy c ...   (local JOIN)

3) Read model        order_view (own component, own table)
   order_id  customer_name  total  <- fed by OrderCreated + CustomerChanged
     123      Asha R.        340
     124      Asha R.         95

The trace: what each path does when Asha renames herself to "Asha Rao" at 10:00:00.

rename at 10:00:00runs offline
composition   10:00:00.1  next page load calls customer svc -> "Asha Rao"   ✓ always current
local copy    10:00:00.4  CustomerChanged applied -> customer_copy.name    ✓ lag 0.4 s
read model    10:00:02.0  projector applies event -> order_view rows       ✓ lag 2 s
customer svc down:  composition ✗ (needs fallback)   copy ✓   read model ✓

Land it Freshness buys you composition, speed buys you a copy, and a cross-cutting view buys you a read model — and each of them replaces the JOIN with a contract.

Likely follow-ups
"API composition at 500 orders per page — what goes wrong and how do you keep it fast?"

The failure is the N+1 call: fetching 500 orders and then calling the customer service 500 times, once per order, which at a few milliseconds each is seconds of latency and 500 times the load on the customer service.

N+1 versus batchruns offline
# illustrative output
N+1:   500 orders -> 500 x GET /customers/{id}   500 x 4 ms = 2000 ms, 500 requests
batch: 40 distinct ids -> GET /customers?ids=... 1 call, ~6 ms
cap 200: 500 orders with 450 distinct ids -> 3 calls (200, 200, 50)

The fix is a batch endpoint — GET /customers?ids=1,2,3 or a POST with a list — that returns all the names in one call, and a cap on batch size, say 200, so the composer makes three calls for 500 orders.

I also deduplicate the ids, because 500 orders may belong to 40 customers.

Beyond that, a short-lived local cache of customer names — a minute — absorbs repeated page loads, and a timeout with a fallback means a slow customer service degrades the page to "customer 123" rather than failing it.

The composition runs the batch calls in parallel when there are several sources. Even so, composition is the right choice only up to moderate volume; above that, the read model wins.

"With the local copy, what happens between the customer renaming themselves and the order service seeing the event?"

For that window — normally under a second, minutes during a consumer incident — the order service shows the old name. Whether that matters is a product question, and for a customer name on an order list it usually does not.

Where it matters is when the copy is used for a decision rather than for display: if the copied field is "account suspended" and the order service accepts an order in the window after suspension, that is a real bug, and the answer is that decisions with consequences are made by the owner synchronously, not from a copy.

The other subtlety is ordering between the copy and the order's own events: if the order service emits OrderCreated with the customer name it holds, a stale name propagates further.

So I copy only what is needed for local reads and decisions that tolerate staleness, and I never re-publish copied data as if I owned it.

"The read model is wrong for 1% of rows — how do you know, and how do you fix it without stopping reads?"

I know because a reconciliation job compares the read model against its sources: for a sample of orders each hour, or the full set nightly, it fetches the current values from the owning services and diffs them against the projected row, reporting mismatch counts by field.

A field that is consistently wrong points at a projection bug; scattered mismatches point at lost or out-of-order events.

The fix without stopping reads is a rebuild into a second table: the projection consumer is started fresh from the beginning of the event history, writing to order_view_v2, while reads continue from the old table; when the new table has caught up to the live position, a flag switches reads to it and the old table is dropped later.

For a partial fix, the reconciliation job itself can repair the mismatched rows in place from the owners' current state, which is cheaper than a rebuild when the count is small.

"When would you pick composition over the copy even for a hot path?"

When freshness is not negotiable and the field changes often.

A stock level shown on the product page is the standard example: a copy would show yesterday's number and the business would rather show none than a wrong one, so the page calls inventory with a short timeout and a fallback of "checking availability".

Another case is data the owner cannot publish widely for privacy or compliance reasons — a credit score, a medical flag — where a copy in every consumer's database is a liability and a synchronous call with access control is the only acceptable path.

And a third is when the consumer needs the data for a tiny fraction of its operations, so keeping a full copy in sync costs more than the occasional call.

In each case the composition call gets the full resilience set — timeout, breaker, bulkhead, fallback — because it is on the hot path by choice.

Q43 · Scenario. "The analytics team asks for read-only credentials to every service's production database so their dashboards can JOIN across them. They say it is read-only, so it is harmless. Your response?"

Reveal answer

Strong answer I would refuse the request as stated and offer the thing they actually need. Read-only credentials still create the hidden contract: the day the orders team renames a column, twelve dashboards break and the orders team discovers it from an angry executive.

Read-only queries are also not harmless to production. Three costs:

  • Locks: an unindexed cross-table scan takes locks in some engines.
  • Resources: it consumes I/O and buffer cache.
  • Vacuum: in PostgreSQL a long-running read holds back vacuum for every table (see Chapter E8).

The alternative is a proper analytics path.

Each service already publishes events; a change-data-capture connector (Debezium) or the event stream itself feeds a warehouse — a columnar store built for JOINs across everything — with a schema the analytics team owns and the service teams commit to via the same schema registry contract.

Freshness is minutes, which dashboards can tolerate, and the production databases never see a dashboard query.

If they need something today, a read replica of each database with a documented, versioned view per service is the interim, with the explicit understanding that the views are the contract and the tables are not.

Picture it what a "harmless" read-only dashboard query does to a production table, and the event-fed path that replaces it.

Make the invisible visible: dead row versions pile up while one old snapshot is open.

table orders while the dashboard query runsruns offline
# illustrative output
time   dashboard txn (xact_start 08:00)   orders table: live / dead-not-removable
08:00  SELECT ... starts, snapshot taken     10,000 / 0
09:00  still running                         10,000 / 8,000   (updates keep making new versions)
10:00  still running                         10,000 / 16,000
VACUUM (VERBOSE) orders:  tuples: 0 removed, 26000 remain, 16000 are dead but not yet removable

The fix: the dashboards read a warehouse fed by events or CDC; production never sees them.

analytics pathruns offline
orders DB -> Debezium / events -> Kafka -> sink connector -> warehouse (analytics team owns)
production tables:  live 10,000 / dead 120   (vacuum keeps up)  ✓
dashboards JOIN across services inside the warehouse               ✓

Land it Read-only access is still a coupling, and the answer is a warehouse fed by events, not a key to the production doors.

Likely follow-ups
"The analytics team says the warehouse will take six months and the dashboards are needed next week. What do you offer?"

The read replica with views, and I would make it a concrete, bounded offer.

Each service gets a read replica of its database — most managed databases give one in an afternoon — and the service team publishes a small set of SQL views in a dedicated analytics schema on that replica, with column names and types they commit to keeping stable; the analytics role has USAGE on that schema and nothing else.

The dashboards query the replica, so the production primary never sees them. The views are the contract: a service may rename a table freely as long as it updates its views, and a view change is announced like an API change.

I would set an expiry on the arrangement — six months — and put the warehouse on the roadmap with the same event streams feeding it, so the interim does not become permanent.

Cross-service JOINs remain impossible on replicas, which is a feature: the dashboards that need them are the ones that justify the warehouse.

"Why is a long-running read on PostgreSQL harmful — explain the vacuum mechanism."

PostgreSQL implements updates by writing a new row version and leaving the old one in place, marked dead once no transaction can still see it. Vacuum is the background process that reclaims dead versions.

why vacuum cannot cleanruns offline
# illustrative output
row id=1: v1 (xmax=T50, dead)   v2 (live)
long reader T40 (snapshot at 40) may still need v1 -> v1 "dead but not yet removable"
every table: versions newer than T40's snapshot cannot be removed while T40 is open

A transaction that started an hour ago may still need to see rows as they were an hour ago, so vacuum cannot remove any row version newer than that transaction's snapshot — on every table in the database, not only the ones the query reads.

While the dashboard query runs, every update-heavy table accumulates dead versions it cannot clean, the tables and indexes bloat, queries slow because they scan dead rows, and in the extreme the transaction id space approaches wraparound.

That is why even a read-only query is not harmless to a production database: it is a pin holding back cleanup everywhere. On a replica the same query blocks replay instead, or is cancelled, depending on hot_standby_feedback, which is a better trade.

"What is the minimal warehouse pipeline you would actually build?"

The events already exist, so the pipeline is a sink.

For each topic the analytics team needs, a Kafka Connect sink connector writes the events into the warehouse — a columnar store such as BigQuery, Snowflake, Redshift, or ClickHouse — as a raw table with one row per event, in the schema the registry defines, with the event's timestamp and id.

That is a configuration file per topic, not code.

On top of the raw tables, the analytics team owns SQL transformations, typically with dbt, that build the current-state tables and the joined views their dashboards want; they can rebuild those from the raw events whenever they change their minds.

For entities whose services do not yet publish events, Debezium change data capture from the service's database into the same warehouse fills the gap, with the understanding that the table shape is not a contract and the service team may change it with notice.

Freshness is minutes, cost is one Connect cluster the platform team probably already runs.

"The security team asks what the risk of read-only production credentials really is."

Beyond the coupling and the vacuum problem, it is a data-exposure problem.

Production databases hold personal data, payment references, and internal fields in raw form, and a read-only credential shared with a team's BI tool gives that tool — and everyone who can configure it — the ability to export any of it.

The warehouse path lets the service team decide what leaves the service: the event schema is the published surface, sensitive fields can be excluded or tokenised at the sink, and access in the warehouse is granted per table with an audit trail.

There is also blast radius: a leaked replica credential exposes one service's data; a leaked "read-only on everything" credential exposes the whole company.

So the refusal is not just about architecture; it is the same data-minimisation principle the security team already enforces at the API layer, applied to the database layer.

Q44. "What does eventual consistency require of the user interface and the API, concretely?"

Reveal answer

Strong answer Eventual consistency means a change made in one service becomes visible in others after a delay — milliseconds normally, minutes during an incident — and the interface has to be honest about that window.

Concretely, the interface has to do five things:

  1. Say it is pending: the API that accepts a change returns 202 Accepted with a status of "processing" and an id, not 200 with a pretence of completion.
  2. Show intermediate states: screens say "payment pending" or "shipping label being created" instead of showing nothing or the stale value.
  3. Read-your-writes: see the next paragraph.
  4. Decide critical rules synchronously: balance checks and seat availability are decided by the owning service, not from a copy.
  5. Show the lag: a metric for read-model age and an alert when it exceeds the promise made to users.

The user's own changes must be visible to them immediately, which is called read-your-writes. Two ways to get it:

  • Optimistic screen: the screen updates from the request it just sent.
  • Owner read: the API that wrote the data also answers the next read from the owning service rather than from a lagging read model, at least for a short window keyed on the user's session.

Picture it one change made at 10:00:00, the table rows on each side while the read model lags, and what the user sees with and without read-your-writes (a CQRS read side).

Make the invisible visible: the write side and the read side hold different rows for a short window.

write side versus read modelruns offline
# illustrative output
time      orders (owner)                 outbox seq   order_view (read model, applied seq)
10:00:00  123 PROCESSING                 48213        123 (none)      applied=48210
10:00:01  123 PROCESSING                 48213        123 (none)      applied=48212
10:00:02  123 PROCESSING                 48213        123 PROCESSING  applied=48213

What you see: the same user reloading at 10:00:01.

without and with read-your-writesruns offline
without:  GET /orders        -> list has no order 123      ✗ "my order vanished"
with:     GET /orders  X-Consistent-To: 48213
          read model applied=48212 < 48213 -> wait up to 500 ms, else fetch 123 from owner
          -> list shows 123 PROCESSING                          ✓

Land it Eventual consistency is a product decision as much as a technical one, and the interface has to carry the "pending" state honestly.

Likely follow-ups
"How do you implement read-your-writes across a write service and a read model, mechanically?"

The write returns a position: the outbox row's sequence number, or the event's offset once the relay has published it, or simply a monotonically increasing version on the aggregate. The client sends that position back on its next read as a header, say X-Consistent-To: 48213.

The read model tracks the highest position it has applied, which it already knows from the events it consumes.

On a read with the header, the read service compares: if the model is at or beyond the position, it answers from the model; if not, it either waits up to a short bound — 500 milliseconds, polling the model's position — or falls back to fetching the specific record from the write service and merging it into the response.

The client learns the position from the write response, so no session store is needed. This gives the one user who just wrote a consistent view, and everyone else the fast path.

"What does 202 Accepted mean for the client, and what does the client do next?"

It means the request was received and recorded, and the outcome will be determined later. The response carries an identifier and a place to look: a Location header or a body with a status URL, such as /orders/123/status, and optionally a Retry-After hint.

202 exchangeruns offline
POST /orders            -> 202 Accepted
                           Location: /orders/123/status   Retry-After: 1
GET  /orders/123/status -> {"state":"PROCESSING"}     (poll 1 s, 2 s, 5 s, cap)
GET  /orders/123/status -> {"state":"CONFIRMED","orderId":123}

The client shows the pending state and then either polls the status URL on a backoff — one second, then two, then five, with a cap — or subscribes to a push channel if the product has one.

The status endpoint returns the current state and, when done, the final result or a link to it. Polling is fine at human scale; for many clients it needs a cache in front of the status endpoint.

The important discipline is that the status endpoint is served by the owner of the state, so it never lies, and that the pending state has a bounded life: if the operation has not resolved within the business's promise, the status says so and offers a next step.

"How do you decide which business rules must be synchronous with the owner?"

I ask what happens if the rule is applied to data that is a few seconds stale, and whether the outcome can be undone.

A rule whose wrong application costs money or breaks a promise and cannot be undone cheaply — is there enough balance, is this seat still free, is this account allowed to trade — must be decided by the owner synchronously, in its own transaction, where it can lock or check-and-set.

A rule whose wrong application is a minor, correctable inconvenience — showing a product as in stock that sells out a second later — can be applied to a copy and corrected downstream, with the correction path designed in.

A middle group can be decided from a copy with a version check: the request carries the version it saw, the owner rejects it if the version moved.

I make the list explicit in the design document, because it is the list of places where eventual consistency is not allowed.

"How do you measure and alert on read-model lag in terms a product person understands?"

In seconds, as "how old is the newest fact this screen can show". The projection consumer records, for each event it applies, the difference between now and the event's creation timestamp, and exports the p50 and p99 as a metric per read model.

The dashboard shows it as a line with a horizontal threshold that matches the promise made to users — five seconds for the order list, a minute for the sales report.

The alert fires when the p99 exceeds the threshold for a few minutes, and the alert text says which screen is affected and by how much. I also expose the same number on the read model's status endpoint so support can see it during an incident.

Absolute consumer lag in messages is the engineering view; age in seconds is what lets a product owner decide whether an incident needs a banner on the site.

Q45 · Design. "Design the read model for the customer's 'My orders' page: order summary, item names, customer's current display name, and live shipping status. Four services own that data."

Reveal answer

Strong answer Requirements: the page loads in under 200 milliseconds, is read a hundred times more often than any order changes, and staleness of a few seconds is acceptable except for the order the user just placed.

Design: a small order-view service owns a denormalised table order_view(order_id, customer_id, placed_at, total, status, items_json, shipping_status, updated_at).

It consumes four event streams:

  • Orders: OrderCreated and OrderStatusChanged.
  • Catalogue: ProductRenamed.
  • Customers: CustomerRenamed.
  • Shipping: ShipmentUpdated.

Each consumer is idempotent (guard table) and updates only its columns. Reads are one indexed query by customer id, ordered by placed_at.

For read-your-writes, the order service's create response includes the full summary and the front end inserts it into the list until the view catches up.

Display name is applied at read time from a small local customer copy rather than stored per order, so a rename does not rewrite thousands of rows.

Trade-offs: another service to run and a rebuild procedure when the schema changes, in exchange for no fan-out calls on the hottest read path.

What I would not do is compose the page from four synchronous calls; at that read volume it makes four services' availability the page's availability.

Picture it the order_view row for order 123 as each of the four event streams updates only its own columns (the CQRS read model).

Make the invisible visible: one row, built up event by event, plus a small customer table joined at read time.

order_view after each eventruns offline
# illustrative output
event (stream, id)                  order_id customer_id total status    shipping  items_json
OrderCreated (orders, e-1)            123       9       340  CREATED   -         [{"p":7,"n":2}]
OrderStatusChanged PAID (orders, e-2) 123       9       340  PAID      -         [...]
ShipmentUpdated PACKED (ship, e-3)    123       9       340  PAID      PACKED    [...]
customer_copy (separate table, one row per customer)
customer_id  display_name
     9       Asha R.   -> CustomerRenamed "Asha Rao" = 1 row update, not N order rows

The trace: a redelivered event must not double-apply.

guard tableruns offline
processed_events (event_id)    e-1 e-2 e-3
redelivery of e-2:  INSERT event_id=e-2 -> duplicate key, skip   ✓
without guard: status written twice (harmless) but a counter column would drift ✗

Land it The read model trades one more component for a page that depends on nothing at request time, which is the right trade for a read-heavy screen.

Likely follow-ups
"The requirement changes: the page must also show the live shipping location from the carrier, updated every minute. What changes?"

The carrier's location is a different kind of data: high-frequency, low-value, and owned by an external party.

I would not push every location update through the event stream into the read model, because it would dominate the write volume of a table whose other columns change rarely.

Instead, the shipping service keeps a small key-value store of the latest location per shipment, updated from the carrier's webhook or a polling job, and the order page fetches location for the visible orders in one batch call with a short timeout and a fallback of the last known status from the read model.

That is API composition for the one field where freshness is the point and staleness has no consequence. The read model keeps the shipment id so the page knows what to ask for.

If the product later wants the location on every order list for every customer at high volume, a cache in front of the location store handles it.

"Under time pressure, what would you cut and ship first?"

I would ship the read model with two of the four streams — OrderCreated and OrderStatusChanged — and compose the rest at read time.

The order view would hold the order summary and items as they were at order time, which is fine because items on a placed order rarely change; customer display name and shipping status would be fetched in two batch calls per page with short timeouts and fallbacks.

That gets the hot query local on day one and leaves two small synchronous dependencies that can be moved into the model later.

What I would not cut is the idempotent consumer with the guard table, because a read model that double-applies events is wrong from the first week and costs a rebuild.

I would also not cut the read-your-writes handling for the just-placed order, because that is the first support ticket. The rebuild procedure can wait until the projection changes for the first time.

"Why not store the display name per order row and update it on rename — what is the actual cost?"

The cost is a write amplification that scales with order history.

rename costruns offline
# illustrative output
per-row name:   rename -> UPDATE order_view SET customer_name=... WHERE customer_id=9   2,000 rows
local table:    rename -> UPDATE customer_copy ... WHERE customer_id=9                  1 row
page read:      SELECT ... FROM order_view v JOIN customer_copy c USING (customer_id)    1 indexed query

A customer with two thousand orders who changes their name triggers two thousand row updates in the view table, in one transaction or in batches, each of which is a row rewrite in PostgreSQL with the accompanying dead tuples and index maintenance.

At a few thousand renames a day across the customer base, that is millions of updates for a field that is read rarely per row.

Storing the name in a small local customer table — one row per customer — and joining at read time on customer id turns that into one update per rename and one indexed lookup per page, which is a join inside one database, so it is cheap.

The rule I take from it is that a denormalised read model should copy data that changes with the row, and reference data that changes independently should be joined locally, not copied per row.

"How do you handle a customer with ten thousand orders on this page?"

With pagination that is stable under change, and an index that matches it.

The query is by customer id ordered by placed_at descending with a limit, so the index is (customer_id, placed_at DESC, order_id) and each page is an index range scan of twenty rows regardless of how many orders exist.

The cursor is the last row's placed_at and order_id rather than an offset, so inserting a new order does not shift the pages the user is scrolling through. The events-json column stays out of the index and is fetched only for the page's rows.

For the total count, which offset-based interfaces want, I store it in the local customer row and increment it on OrderCreated rather than counting ten thousand rows on every load.

A business customer with that many orders also usually wants filters — by date range or status — which the same index serves as long as the filter columns are leading or the result is small.

Q46. "Explain two-phase commit properly, then tell me the three reasons service architectures avoid it."

Reveal answer

Strong answer Two-phase commit is a protocol for one atomic transaction across several databases, coordinated by a transaction manager.

  1. Phase one, prepare: the coordinator asks each participant to prepare. Each writes the transaction to its log, holds its locks, and votes yes or no.
  2. Phase two, decide: if every vote is yes the coordinator writes a commit record and tells everyone to commit; otherwise it tells everyone to abort.

It works, and the Java standard for it is XA through JTA. Services avoid it for three reasons.

First, availability: between prepare and the coordinator's decision, every participant holds its locks, so a slow or crashed coordinator freezes rows in every database until it returns — the system's availability collapses to the coordinator's.

Second, coupling in time: every participant must be up and fast at the same moment, which is exactly the property services were split to escape, and the protocol is synchronous and blocking through its whole length.

Third, coverage: Kafka, HTTP services, Redis, cloud APIs, and most managed databases do not participate in XA, so 2PC cannot include the calls you actually make. Sagas give up atomicity and buy availability by making compensation an explicit, visible, retryable step. the Distributed Systems primer covers the consensus story underneath.

Picture it a 2PC between the order and payment databases with the coordinator crashing after prepare, and the same checkout as a saga (Pattern: Saga Orchestration).

Make the invisible visible: lanes and the locks each database holds.

2PC with coordinator crashruns offline
# illustrative output
Coordinator        Orders DB                    Payments DB
 PREPARE  ------>  log + lock row 123, vote YES
 PREPARE  ------------------------------------> log + lock charge row, vote YES   ✓
 (crash before writing the decision)                                              ✗
                   row 123 locked ...           charge row locked ...   waiting, "in doubt"
pg_prepared_xacts (on each database)
 transaction  gid         prepared             owner
   774        tx-123      10:00:00.2           app
Everyone else touching these rows blocks until the coordinator is back, or a human runs COMMIT PREPARED / ROLLBACK PREPARED.

The fix: a saga commits each step locally and compensates, so no lock is held across services.

same checkout as a sagaruns offline
orders:   INSERT 123 PENDING  commit ✓      (lock released)
payment:  INSERT charge       commit ✓      (lock released)
payment down? orders row stays PENDING, orchestrator retries; nobody is locked   ✓

Land it 2PC buys atomicity by holding everyone's locks hostage to a coordinator, and that is the wrong trade for a system built to stay available.

Likely follow-ups
"What happens at each crash point in 2PC — participant after prepare, coordinator after prepare?"

A participant that crashes after voting yes has already written the prepared transaction to its log with its locks, so on restart it recovers the prepared state and waits for the coordinator's decision; its locks stay held through the restart, which is the in-doubt state.

crash pointsruns offline
crash point                        outcome
participant before voting          timeout = NO vote, all abort      ✓
participant after YES              recovers prepared tx, locks held, waits    (in doubt)
coordinator after votes, no log    all participants blocked                    ✗
coordinator log lost               manual COMMIT PREPARED / ROLLBACK PREPARED

A participant that crashes before voting is treated as a no vote by the coordinator's timeout, and everyone aborts.

The coordinator crashing after collecting votes but before writing its decision is the bad case: every participant is prepared, holding locks, and none can decide on its own — a participant that unilaterally committed might contradict one that unilaterally aborted — so they all wait until the coordinator returns and reads its log.

If the coordinator's log is lost, a human resolves each in-doubt transaction by hand, using commands such as COMMIT PREPARED in PostgreSQL. That blocking window is why 2PC's availability equals the coordinator's, and why the protocol is called blocking.

"Is XA ever the right choice in a modern Java service?"

Rarely, and in a narrow shape: one service that must write atomically to two resources it fully controls and that both support XA, such as a relational database and a JMS broker like ActiveMQ Artemis, where the alternative — an outbox — would be more code than the team wants for a low-volume path.

Even then the transaction manager needs a durable log, which in Spring Boot means adding Narayana or Atomikos and its recovery configuration, and the recovery procedure has to be tested by killing the process mid-commit.

The moment the second resource is Kafka, an HTTP service, or a managed cloud service without XA support, the option is gone, and that is most of the modern stack.

So my honest answer is that XA belongs in the legacy-integration toolbox — a message-driven bean talking to a mainframe queue and an Oracle database — and the outbox plus idempotent consumer is the default for everything I would build today.

"How is a saga different from 2PC in what it guarantees — what do you actually lose?"

2PC gives atomicity and isolation across the participants: either every write commits or none does, and no one sees a partial state.

A saga keeps atomicity in a weaker form — eventually every step has either completed or been compensated — and gives up isolation entirely, because each step commits locally and is visible before the saga finishes.

So with a saga you lose the guarantee that nobody observes the middle: a report can count a charged-but-not-shipped order, a concurrent operation can act on a reservation that is about to be released.

You also lose automatic undo: a compensation is application code you write and test, and it can fail. What you keep is that each participant is available and independent — no locks are held across the network, and a slow participant delays only its step.

The trade is atomicity-with-locks for availability-with-visible-intermediate-states, and the design work in a saga is deciding what those states look like.

"What about newer approaches — can a single distributed database avoid the choice?"

Distributed SQL databases such as CockroachDB, Spanner, and YugabyteDB do give serialisable transactions across nodes, and internally they use two-phase commit with consensus-replicated participants so the coordinator's crash does not block — the blocking weakness of classic 2PC is solved by replicating the coordinator's decision.

That is a real advance, and it means a single service can span many nodes with real transactions.

What it does not change is the service boundary: if orders and payments are two services with two schemas, putting them in one distributed database recreates the shared database with all its coupling, whatever the database's consistency guarantees.

So these databases solve the scaling problem for one service's data; they do not solve the problem of two teams' data, which is an ownership problem. The saga is still the tool when the boundary is a team boundary.

Q47 · Scenario. "Support reports an order that shows PAID in the order service while the payment service has no record of a charge for it. Diagnose."

Reveal answer

Strong answer The symptom is two services disagreeing about one fact, which means the fact reached one of them by a path that does not go through the other's committed state.

Evidence to collect: the order's event history (what event set it to PAID and when), the payment service's idempotency-key table for that order id, and the trace for the checkout request.

Causes ranked:

  1. Reply later rolled back: the order service marks itself PAID on a synchronous call's response that was later rolled back in payment — a commit that failed after the reply was sent, or a payment written to a replica that lost it on failover.
  2. Dual write: a "PaymentCompleted" event was produced from a dual write, and the event went out while the payment insert did not commit.
  3. Bug: the order service sets PAID on the request rather than on the confirmation.

The fix for this order is a reconciliation: treat payment's ledger as the truth, revert the order to PENDING, and re-run the charge with the same idempotency key so the customer is not double-charged.

Prevention: PAID may only be set by consuming a PaymentCompleted event that came from payment's outbox, never from a synchronous reply; and a nightly reconciliation job that compares the two ledgers and alerts on any drift, because it will find the next bug before support does.

Picture it the rows of the order, payment and outbox tables at the moment the two services disagree, and after the reconciliation fix (see Pattern: Outbox).

The trace: a dual write where the event goes out and the payment insert does not commit.

dual write failureruns offline
# illustrative output
payment svc:  BEGIN
              INSERT charge(order 123, 340)       (not yet committed)
              publish PaymentCompleted(123)  -> broker offset 88   ✓ event is out
              COMMIT fails (connection drop)                        ✗
order svc:    consumes offset 88 -> UPDATE orders SET status='PAID' ✓

What you see: the table state of both services.

tables at the moment of disagreementruns offline
orders (order svc)         payments (payment svc)        outbox (payment svc)
id   status                 order_id  amount  idem_key     (no row: nothing committed)
123  PAID                   (no row for 123)               ✗ orders say PAID, payments say nothing

The fix: the order is PAID only from an event written to the outbox in the same transaction as the charge, and reconciliation repairs this one.

after the fixruns offline
payments                                   outbox
order_id amount idem_key  status           id  topic     key  published
 123     340    ord-123   CAPTURED          9  payments  123  true      <- exists only if the charge committed ✓
orders: 123 PENDING -> re-run charge with idem_key ord-123 -> one charge, then PAID   ✓

Land it The service that owns the money is the only source of "paid", and any other service learns it from that service's committed events, not from a reply.

Likely follow-ups
"You set PAID only from the PaymentCompleted event, and the drift reappears the next month. What next?"

Then the event is arriving for a payment that payment itself later loses, so I look inside the payment service.

failover windowruns offline
# illustrative output
10:00:00.0  primary commits charge 123 + outbox row; replica has not received it yet
10:00:00.1  relay publishes PaymentCompleted(123)  -> order service sets PAID   ✓
10:00:00.3  primary dies; replica promoted, replay position before 10:00:00.0
payments on new primary: no row 123          orders: PAID                        ✗

The likely mechanism: payment writes the charge and the outbox row in one transaction, the relay publishes PaymentCompleted, and then the payment record disappears — a failover to a replica that had not received that commit, which happens with asynchronous replication when the primary dies in the window between commit and replication.

The outbox event survived because it had already been published. The evidence is the timing: the affected payments cluster around a failover, and the replica's replay position at promotion is before those commits.

The fix is synchronous replication for the payment database, or at least for its commit — PostgreSQL's synchronous_commit=on with a synchronous standby — so a commit is acknowledged only when the standby has it.

The reconciliation job is what catches this class, because the event stream and the ledger disagree by exactly the lost window.

"How would the nightly reconciliation actually work between two services' data?"

Each service exposes a bulk read of its own facts for a time window, designed for this purpose: orders returns the order ids marked PAID with the payment reference and the paid-at time for yesterday; payment returns the charge ids, order ids, amounts, and status for the same window.

The job fetches both lists, joins them in memory or in a small scratch database, and produces three sets: orders PAID with no charge, charges with no PAID order, and pairs whose amounts differ.

Each set goes to a table with a status and an owner, and an alert fires if any count is above a small tolerance for in-flight items near the window edge. The endpoints are paginated and cheap because they read by an indexed timestamp.

What makes it a real control rather than a report is that someone is on the rota to clear the table, and that a repeated cause becomes a ticket for the owning team.

"What is wrong with setting PAID from the synchronous reply, exactly — the reply came from payment, after all?"

The reply is a statement about the payment service's intent at the moment it wrote the response, not about its committed state.

In a normal servlet flow, the response is written after the transaction commits, so it is usually right — but there are windows where it is not: a framework that commits after the response is flushed, a commit that fails on a serialisation conflict or a connection drop after the response was queued, an asynchronous replication failover that loses the commit, or a bug where the provider's response was accepted before the ledger insert.

The committed event from the outbox has none of those windows, because the outbox row is in the same transaction as the charge: if the event exists, the charge committed.

So the synchronous reply is a good signal for the user's screen — "payment accepted" — and the event is the only acceptable source for a state that has money consequences.

"How do you fix this one order without double-charging the customer?"

I first establish whether the customer was actually charged, by asking the payment provider directly with the order's reference, because payment's own record may be missing while the provider's charge stands.

If the provider has no charge, the order is reverted to PENDING and the charge is re-run with the original idempotency key, which means the payment service will attempt it once and record it properly this time; the customer sees one charge.

If the provider does have a charge that payment lost, I do not re-run anything: I insert the missing payment record from the provider's data through an administrative path that records who did it and why, and the order stays PAID. The idempotency key is what makes the first path safe; the provider query is what makes the second path necessary.

Either way the order's history gets a note so support can explain it later.

Q48. "Reference data — countries, currencies, tax codes — is needed by every service. Who owns it and how does everyone else get it?"

Reveal answer

Strong answer Reference data has two properties that change the usual answer: it is small, and it changes rarely and on a schedule rather than per request.

So the rule "call the owner" is the worst fit — you do not want every service calling a country service on every request for data that changed last in 2011.

The pattern is a single owning service, often a small "reference data" service or the configuration repository.

It publishes the full dataset as a versioned artifact or a compacted Kafka topic. Every consumer holds a complete local copy in memory, refreshed on a schedule or on a change event.

A compacted topic — where Kafka keeps the latest value per key forever — is the neatest: a new service instance reads the topic from the beginning at startup and has the whole dataset in seconds.

For data that is both small and effectively frozen, such as ISO country codes, shipping it as a library is fine, with the same version-drift caveat as any shared library.

What I avoid is each service maintaining its own hand-edited copy, because tax codes drift and the drift shows up as a customer being charged two different rates by two services.

The senior point is that ownership still matters: one team is responsible for correctness and publishing, even if the data is copied everywhere.

Picture it a compacted reference topic with offsets and keys, a new instance loading it at startup, and an effective-dated tax rate.

Make the invisible visible: the topic keeps the latest value per key, and a new instance reads all of it before reporting ready.

compacted topic reference.taxruns offline
# illustrative output
offset  key    value                               compaction keeps
  10    DE     {"rate":19,"from":"2007-01-01"}     (superseded)
  11    FR     {"rate":20,"from":"2014-01-01"}     kept
  12    DE     {"rate":19,"from":"2007-01-01"}     (superseded)
  13    DE     {"rate":21,"from":"2027-01-01"}     kept   <- announced early, effective-dated
new instance: reads offset 0..13 (end offset seen at start = 14)  -> ready only at 14   ✓

The trace: what two instances compute for a German order on 2026-12-31 and on 2027-01-01.

effective-dated lookupruns offline
order at 2026-12-31 23:59  -> latest record with from <= order time: 19%   ✓ on every instance
order at 2027-01-01 00:00  -> 21%                                          ✓ on every instance
instance one minute behind on the topic still has both rows -> same answer  ✓
hand-edited copy in service X still says 19% after the change              ✗ two rates for one customer

Land it One owner publishes, everyone copies and caches, because slow-changing shared data should never be a runtime dependency.

Likely follow-ups
"A tax code changes at midnight. How do you make every service switch at the same moment?"

You cannot make twenty services switch at the same instant with a push, and you should not try.

The right shape is effective-dated data: the reference record carries a valid-from timestamp, and the owner publishes the change days ahead, so every consumer already holds both the old and the new rate and picks the right one by comparing the transaction time with valid-from.

Then the "switch" is a function of the clock, not of delivery timing, and a consumer that is a minute behind on the topic still applies the right rate.

For reference data without effective dating, I accept a propagation window of seconds and design around it: the service that actually computes tax for money purposes — one service, the pricing or tax service — is the authority, and the copies in other services are for display and estimates.

A reconciliation on the day of the change confirms every consumer has the new version by checking the dataset version each service reports.

"How does a new instance get the dataset at startup without hammering anything, and what if the topic is unavailable?"

From a compacted topic, the instance reads from the earliest offset to the current end, which for a few thousand keys is seconds and costs the broker almost nothing.

startup readinessruns offline
start: end offset = 14, local snapshot = none
read 0..13 -> dataset size 2 keys; ready=true at offset 14   ✓
broker down at start: load snapshot from disk, ready=true, flag "possibly stale"  (or refuse to start)

The instance reports ready only after it has reached the end offset it observed at startup, so it never serves with a partial dataset.

If Kafka is unavailable at startup, the instance can start from a local snapshot — the last dataset it wrote to disk or to a small cache — and mark itself as running on possibly-stale data, or it can refuse to become ready, depending on how critical freshness is.

For a library-shipped dataset, none of this applies: the data is in the jar.

The choice between topic and library is largely this startup question: if the platform can tolerate a startup dependency on the broker, the topic keeps everyone fresh; if not, the library plus a scheduled refresh is safer.

"Where do you draw the line between reference data and domain data?"

Reference data is small, changes on a schedule set by an outside authority, has no per-customer or per-transaction state, and is read by everyone: countries, currencies, tax rates, units, carrier codes.

Domain data is owned by a business capability, changes per event, and has consequences when stale: prices, stock, customer status.

The line blurs in the middle — a product catalogue is read by everyone but changes constantly, a list of shipping zones changes rarely but is owned by a team with business rules.

My test is whether a change to the data needs a business decision by the owning team or is simply a fact from outside; facts from outside are reference data and get the copy-everywhere treatment, decisions get the owner-and-events treatment.

When in doubt I treat it as domain data, because the cost of a synchronous or event-driven owner is lower than the cost of twenty stale copies of something that mattered.

Q49 · Design. "Move the orders tables out of the monolith's shared database into the new order service's own database, without downtime and without a big-bang cutover."

Reveal answer

Strong answer Assumptions: the monolith still runs, dozens of code paths touch the orders tables, and the business cannot pause. Design, in phases.

Phase one, find every reader and writer of the orders tables in the monolith and route them through one internal module — a repository interface — so there is a single choke point. It is a refactor with no behaviour change.

Phase two, stand up the order service with its own database and schema, and feed it from the old table. Two options:

  • Dual write: each write goes to both the old table and the new service. Acceptable only here because it is temporary and reconciled.
  • Change data capture (better): CDC from the old table feeds the new database, so the monolith stays the single writer.

Phase three, backfill history into the new database and run a reconciliation job that compares row counts and checksums nightly until they match for a week.

Phase four, switch reads to the new service behind a feature flag, one screen at a time, watching latency and error rate.

Phase five, switch writes so the order service is the only writer and CDC runs in reverse to keep the old table fed for any laggard reader. Phase six, delete the old readers, then the old table.

The trade-off is weeks of double running; what I would not do is a weekend migration with a maintenance window, because the first reader nobody found will fail on Monday.

Picture it the old and new orders tables through the phases, with counts and checksums, a hidden writer showing up in reconciliation, and the flag-based read switch (Pattern: Strangler Fig).

Make the invisible visible: the table state of both databases at each phase.

migration phasesruns offline
# illustrative output
phase                         monolith.orders   order_svc.orders   readers         writers
1 choke point                 rows 1,200,000    (none)             old             old (via module)
2-3 CDC + backfill            1,200,000         1,199,998 growing  old             old
4 reads on flag 1% -> 100%    1,200,350         1,200,350          new (per flag)  old
5 writes switched             frozen / read-only 1,200,900          new             new (reverse CDC to old)
6 cleanup                     dropped           1,201,500          new             new

What you see: the reconciliation job finds the hidden writer.

nightly reconciliationruns offline
# illustrative output
night 1: count 1,200,350 vs 1,200,348  mismatches=2  both updated_at 02:00:03 (timing) -> compare rows older than 5 min
night 2: mismatches=14  all status column, all written by batch_job_x (raw SQL, no module) ✗
fix: batch_job_x goes through the module
night 3: mismatches=0   ... 7 clean nights -> proceed                       ✓

Land it Migrate the readers first behind a flag and the writers last behind reconciliation, so every step is reversible and the cutover is a non-event.

Likely follow-ups
"The reconciliation finds a mismatch every night and never gets to a clean week. What next?"

I stop treating the mismatches as noise and classify them. A mismatch that appears on rows updated near the moment of comparison is timing, and I fix the comparison by snapshotting both sides at a consistent point — compare rows with updated_at older than five minutes.

A mismatch concentrated on particular columns points at a transformation bug in the copy path or a type difference, such as a timestamp without timezone on one side.

A mismatch on rows written by a particular code path points at a writer that bypasses the choke point — an old batch job, a stored procedure, a raw SQL update in an admin tool — and that is the one that matters, because it would have been a silent divergence after cutover.

I find it from the database's statement log filtered to the orders tables, fix the writer to go through the module, and the next night's run tells me whether that was the last one.

Reconciliation that never goes clean is a finder of hidden writers, not a failing test.

"Why is CDC better than the dual write in phase two, concretely?"

With the dual write, the monolith writes to the old table and then calls the new service, and the two writes have a crash point between them: a failure after the first leaves the new database behind, and a failure of the second after the first commits needs a retry the monolith must persist.

dual write versus CDCruns offline
dual write: INSERT old ✓ -> call new service ✗ (timeout)   new DB is behind, monolith must persist a retry
CDC:        INSERT old ✓ commit -> Debezium reads the log -> new DB INSERT   ✓ no crash point in the write path

It also adds the new service's latency and availability to every order write during the migration.

With change data capture, the monolith keeps writing only to its own table inside its own transaction, exactly as before, and Debezium reads the committed changes from the database log and applies them to the new database, so there is no crash point and no new dependency in the write path.

The copy lags by milliseconds and is guaranteed complete because it comes from the log. The costs are the connector to run and a transformation step if the new schema differs from the old, which it usually does and which is the real work.

"How do you make the read switch safe, screen by screen?"

Each screen's read path checks a feature flag that names the screen and returns a percentage, so I can send 1% of order-history page loads to the new service and the rest to the old table, then 10%, then all.

While both paths exist, I run a shadow comparison for a sample: the old path's result and the new path's result for the same request are diffed in the background and mismatches are logged with the request, which catches transformation bugs the reconciliation missed because it compares rows, not responses.

The dashboards for the screen show latency and error rate split by path. Rollback is the flag set to zero, which takes effect on the next request with no deploy.

Order of screens: read-only, low-traffic, internal screens first — an admin lookup — then customer-facing lists, then anything that reads orders inside a transaction, because those are the paths where the new service's latency matters most.

"What would you cut if the business needs this done in a month rather than a quarter?"

I would cut the duration of each phase, not a phase.

The choke-point refactor is the one that cannot be skipped, because without it the hidden writers are found in production; but it can be done for the write paths only, leaving readers to be found by the statement log.

CDC can be replaced by a simpler one-shot backfill plus a short dual-write window if a Kafka Connect cluster is not already available, accepting a reconciliation-and-repair step at cutover.

The screen-by-screen read switch can become two flags — internal screens, customer screens — rather than one per screen.

And the reverse CDC after the write switch can be replaced by a hard rule that the old table is read-only from that moment, with the laggard readers being fixed under time pressure.

What I would refuse to cut is the nightly reconciliation and the flag-based rollback, because they are what make a fast migration survivable.

Q50. "When would you deliberately NOT give a service its own database?"

Reveal answer

Strong answer Three cases.

  1. Early in a split: the goal is to prove the service boundary before paying for data migration. The service gets its own schema and its own credentials in the existing database instance, and no other code may touch that schema.
  2. Services that always change together: they must be transactionally consistent, which is usually a sign they are one service, and the honest fix is to merge them rather than to share a database. As an interim, sharing one database with strict schema ownership is better than a broken saga.
  3. Cost: a small platform with fifteen services and fifteen managed database instances pays fifteen times the base fee and fifteen backup schedules for tiny datasets. One well-run instance with separate logical databases is a rational choice, accepting that one service's runaway query can slow the others.

In every case the non-negotiable part is one writer per table and no cross-schema queries, enforced by database permissions rather than by convention. What I would never do is share tables, because that recreates the hidden API the split was meant to remove.

Picture it one database instance with schemas per service, enforced by roles (Pattern: Database per Service), and what it does and does not isolate.

The setup: one instance, schemas and roles, connection limits.

permissionsruns offline
CREATE SCHEMA orders AUTHORIZATION orders_svc;
REVOKE ALL ON SCHEMA orders FROM PUBLIC;           -- no other role gets USAGE
ALTER ROLE orders_svc CONNECTION LIMIT 40;         -- Result: caps this service's share of max_connections

What you see: the wall holds for data, but not for shared CPU and cache.

instance viewruns offline
# illustrative output
payments> SELECT * FROM orders.orders;
ERROR:  permission denied for schema orders                         ✓ wall holds
connections: orders_svc 40/40, payments_svc 25/40, shipping_svc 12/40 (max_connections=200)
orders_svc runs an unindexed query: CPU 95%, buffer cache churn -> payments p99 +300 ms   ✗ not isolated

Land it Share the server if you must, share the schema never — the rule is ownership, and hardware is a separate budget decision.

Likely follow-ups
"With one instance and fifteen schemas, how do you stop one service's load from hurting the others?"

Partly, with the tools the database gives. Each service's connection pool is capped so the sum fits in max_connections with headroom, and a per-role connection limit — ALTER ROLE orders_svc CONNECTION LIMIT 40 — enforces it from the database side.

Statement timeouts per role stop a runaway query from holding resources for minutes. A pooler such as PgBouncer in front gives per-database pools with queueing.

What cannot be isolated is the shared buffer cache, CPU, and I/O, so a badly indexed query in one schema still slows the others; the defence is the same query hygiene any database needs, plus monitoring per role so the culprit is visible.

When a service's load or its incidents start showing up in the neighbours' latency graphs, that is the signal to move it to its own instance, and the schema-per-service layout makes that move a dump and restore rather than a redesign.

"How do you migrate a schema out of the shared instance into its own database later?"

Because the schema already has one writer and no cross-schema references, the move is a data migration, not an architectural change.

schema moveruns offline
t0  restore dump of schema orders into new instance          (service still on old)
t1  logical replication: old.orders -> new.orders, lag 0.2 s
t2  stop service, wait lag=0, flip connection string, start    (seconds)   ✓
t3  rollback window: reverse replication optional
if foreign keys into schema payments existed: this move is a full migration ✗

The steps: create the new instance and restore a dump of the schema into it; set up logical replication from the old instance's schema to the new one so it stays current — PostgreSQL's native publication and subscription on the tables of that schema works for this; verify counts and checksums; then in a short window, stop the service, wait for replication to drain, flip the service's connection string to the new instance, and start it.

The stop is seconds to a minute. Reverse replication for a rollback window is optional but cheap.

The reason this is easy is precisely the rule I would not bend: if the schema had foreign keys into another schema or another service read its tables, the same move would need the full six-phase migration.

"Is a 'shared cluster with schema per service' a good default for a new platform, or a compromise?"

For a new platform under, say, ten services and one team of operators, I would call it a good default, not a compromise, as long as the ownership rules are enforced by permissions from the first day.

It gives one thing to back up, one thing to upgrade, one set of monitoring, and a fraction of the cost, while the services already own their data in the only way that matters.

The compromise is in failure isolation and in capacity ceilings, and both have clear signals: the first time one service's incident becomes another's, or the first time the instance's size is set by the largest service's peak, the affected service moves out.

What makes it a compromise rather than a default is skipping the enforcement — one shared role, tables in public, foreign keys everywhere — because then it is just a shared database with a nicer name.

Drill · Sagas

This group tests whether you can run a multi-service business operation to completion, in both directions, under crashes, timeouts, and concurrent changes.

Q51. "Define a saga, and explain the difference between compensation and rollback in a way a junior would remember."

Reveal answer

Strong answer A saga is a business operation made of a sequence of local transactions, each in its own service and its own database.

Every step has a compensating action that reverses its effect if a later step fails.

Order created, card charged, stock reserved; if stock fails, refund the card and cancel the order. The difference from rollback is the travel-agent picture.

If the car rental fails, the agent does not un-book the flight as though it never happened; the flight was really booked, and the agent books a cancellation. That is compensation: a new, committed, visible action that undoes the business effect of an earlier committed action.

Rollback is what a database does inside one transaction: the earlier work simply never becomes visible. The consequences of the difference are what matter.

Four consequences follow:

  • Compensations can fail and must be retried.
  • They are visible: other people can observe the middle (the customer's statement shows a charge and a refund).
  • They must be idempotent.
  • Some actions cannot be compensated at all — a sent email, a shipped parcel — so those go last.

A saga therefore gives up atomicity and isolation to keep every service available and independent, and the design work is deciding what the world looks like in the middle.

Picture it the same failed checkout done as a rollback and as a compensation, with the rows of every table visible (Pattern: Saga Orchestration).

Make the invisible visible: the rows each service has committed at each step when stock fails.

compensation, row by rowruns offline
# illustrative output
step                       orders           payments                  inventory
1 create order             123 PENDING      -                         -
2 charge card              123 PENDING      ch-1 CAPTURED 340         -
3 reserve stock FAILS      123 PENDING      ch-1 CAPTURED 340         ✗ insufficient
4 compensate: refund       123 PENDING      ch-1 CAPTURED 340         -
                                            rf-1 REFUNDED 340         (new row, charge still there)
5 compensate: cancel       123 CANCELLED    ch-1, rf-1                -
a DB rollback would leave payments with NO row at all; here both rows stay and the statement shows both

What you see: what the customer and a report see in the middle.

visible middleruns offline
card statement after step 2:  -340 (charge)          report at step 3: counts order 123 as paid ✗
card statement after step 4:  -340, +340 (refund)   final state: CANCELLED ✓

Land it Rollback means nobody ever saw it; compensation means everyone saw it and you visibly put it right — and that difference drives every saga decision.

Likely follow-ups
"Give me an example of an action that cannot be compensated, and what you do about it in a saga."

Sending an email, shipping a parcel, notifying a third party's webhook, or posting to a public ledger — once done, the world has seen it and no later action makes it unseen. For these the saga has two options.

Put the action after the pivot, so it runs only once the saga is committed to completing and is retried until it succeeds; a confirmation email belongs there.

Or, if it must happen earlier, replace the action with a reversible stand-in: reserve a parcel pickup rather than dispatching it, send a "we are preparing your order" message rather than "your order has shipped", authorise a card rather than capturing it.

The business then accepts that a failure after that point produces a follow-up message — "your order was cancelled" — rather than a clean undo. The rule for juniors is: if you cannot write the compensation, the step goes last, or it becomes a reservation.

"Why must a compensation be idempotent, and what does that look like for a refund?"

Because the orchestrator will retry it. A compensation runs when something has already gone wrong, so the environment is often degraded — the payment service is slow, the network is flaky — and the refund command is likely to time out and be re-sent.

idempotent refundruns offline
refund(id="refund-for-charge-9f3a")  attempt 1 -> timeout (but processed)   ?
refund(id="refund-for-charge-9f3a")  attempt 2 -> returns stored result, no second refund   ✓
without the id: attempt 1 + attempt 2 = customer refunded twice               ✗

If each send produced a refund, a customer would be refunded twice, which is the saga losing money while trying to do the right thing.

Idempotent refund means: the refund command carries a deterministic id derived from the charge — refund-for-charge-9f3a — the payment service stores it, and a repeat returns the stored result. Most card processors accept an idempotency key on refunds for exactly this reason.

The same applies to releasing a reservation: releasing an already-released reservation returns success rather than an error, so the orchestrator can retry without a special case for "already done".

"How do you explain the 'middle state' to the business — what do they need to decide?"

I show them the states an order can be in and ask, for each, what the customer sees, what support says, and how long it may last.

Between charge and shipment confirmation the customer has paid and has nothing; the business decides whether the order page says "confirmed" or "processing payment", and how long that may last before someone is alerted — an hour, a day.

Between a failed step and a completed compensation, the customer may see a charge and no order; the business decides on the wording of the message and whether an automatic apology credit is issued.

And for a compensation that fails permanently, someone must own the manual path.

These are product decisions that engineers tend to make silently by writing status strings; making them explicit is most of the value of the saga conversation, because the code only encodes what was decided.

Q52. "Choreography versus orchestration — mechanism, trade-offs, and your rule for choosing."

Reveal answer

Strong answer In choreography there is no coordinator: each service reacts to events and emits its own.

  1. Orders publishes OrderCreated.
  2. Payment consumes it, charges, and publishes PaymentCompleted.
  3. Inventory consumes that and publishes StockReserved or StockFailed.
  4. Payment consumes StockFailed and refunds.

Each service knows only its own inputs and outputs, which is loose coupling at its best. The costs appear with growth:

  • No status: by eight steps nobody can answer "where is order 123 right now?" without reading six services' logs.
  • No whole flow: it exists nowhere as a readable whole.
  • Hard changes: adding a step means changing which events several services listen to.

In orchestration one component holds the saga's state and issues commands in sequence — charge, then reserve, then on failure refund — and records each reply.

The flow is readable in one place, status is a query on one table, and adding a step is a local change.

The costs: the orchestrator is a single point every step depends on, it must be persisted and resumable after a crash, and it can drift into holding business logic that belongs in the participants.

My rule: choreography for two to four steps with no branches, orchestration for anything longer, anything with branches or timeouts, and anything a human will need to inspect.

Picture it the same two-step failure as choreography (events between services, no state anywhere) and as orchestration (one saga_state row), linking Pattern: Saga Choreography and Pattern: Saga Orchestration.

Make the invisible visible: events on topics for the choreography, one table row for the orchestration.

choreography versus orchestrationruns offline
# illustrative output
CHOREOGRAPHY (no owner of the flow)
 orders.events      off 40  OrderCreated(123)
 payments.events    off 77  PaymentCompleted(123)
 inventory.events   off 12  StockFailed(123)
 payments.events    off 78  PaymentRefunded(123)
 "where is order 123?" -> grep 3 services' logs/topics

ORCHESTRATION
 saga_state   saga_id  order_id  step           status         updated
              s-9      123       RELEASE_PAY    COMPENSATING   10:00:07
 "where is order 123?" -> SELECT * FROM saga_state WHERE order_id=123   ✓ one row

The trace: a payment timeout is only visible to someone who is counting.

timeoutruns offline
choreography: OrderCreated(123) sent 10:00:00 ... no PaymentCompleted by 10:00:30 -> nobody notices   ✗
orchestration: saga_state.deadline = 10:00:30, sweeper at 10:00:31 queries payment             ✓

Land it Choose by how many steps and how often someone will ask "where is it now?" — beyond four steps, that question decides it.

Likely follow-ups
"Where does the orchestrator live — in the order service, or as its own service?"

In the service that owns the aggregate the saga is about, which for checkout is the order service.

The saga's state is part of the order's lifecycle, and putting the orchestrator there means its state table, its outbox, and the order row are in one database and can be updated in one transaction.

A separate "saga service" that orchestrates everyone's sagas becomes a central point every team depends on and a home for business logic nobody owns — the distributed monolith in another shape.

The exception is a platform-level workflow engine such as Temporal, which is infrastructure: the engine is shared, but each team's workflow code is deployed by that team and owns its own definitions.

So the rule is that orchestration logic is owned by the team whose business process it is, and the engine, if any, is shared the way the message broker is.

"How does the orchestrator avoid absorbing the participants' business logic?"

By issuing commands that name an outcome, not a procedure, and by treating every reply as a decision the participant made.

The orchestrator says "reserve stock for these items" and accepts "reserved" or "insufficient"; it does not decide which warehouse, whether partial reservation is allowed, or what a backorder means — inventory decides those and encodes them in its reply.

A smell is an orchestrator that branches on the participant's internal fields, such as inspecting the warehouse code to decide the next step, or that validates a participant's inputs on its behalf.

The code review rule I use is that the orchestrator's state machine should be readable by a product person as the business process and contain no rules about any one domain.

When a rule genuinely belongs to the process — "premium customers get free shipping" — the process owns it and it lives in the orchestrator, and that is fine as long as it is the process's rule.

"You said choreography for two to four steps. A three-step saga has a timeout on one step — does that change the answer?"

It nudges it toward orchestration, because a timeout needs someone to be counting.

In choreography nobody holds the saga's state, so "payment has not answered in 30 seconds" is a fact no service can observe without adding a timer and a record of what it is waiting for — at which point that service has become a small orchestrator for that step.

It can be done: the order service, on emitting OrderCreated, also schedules a check, and if no PaymentCompleted or PaymentFailed has arrived by the deadline it queries payment and emits the appropriate event.

But once two of the three steps have timeouts, the order service is tracking the whole saga anyway, and an explicit orchestrator with a state row is simpler than timers scattered across handlers.

So my rule has a rider: choreography while the flow is linear and every step is either fast or safe to leave pending; the first timeout or branch is the point to reconsider.

"How do you test an orchestrated saga?"

At three levels. Unit tests of the state machine: given state STOCK_RESERVED and reply PaymentFailed, assert the next command is ReleaseStock and the next state is COMPENSATING — these are fast, exhaustive, and cover every transition including duplicate and stale replies.

state machine unit test tableruns offline
state            reply           next command   next state
STOCK_RESERVED   PaymentFailed   ReleaseStock   COMPENSATING   ✓
COMPENSATING     PaymentFailed   (ignore, stale) COMPENSATING   ✓ duplicate

Integration tests with the real database and an embedded broker: run the saga end to end with stubbed participants, and inject a crash — kill the orchestrator between the state update and the outbox publish, then restart — to prove the recovery sweeper resumes it correctly.

And a contract test per participant, so the orchestrator's command schema and the participant's reply schema are checked against each other in CI. In staging I add a chaos run: participants made slow or unavailable at random while sagas run, with an assertion at the end that every saga is in a terminal state and every charged order shipped or was refunded. The last one is the test that finds real bugs.

Q53 · Design. "Design the checkout saga across order, payment, inventory, and shipping as an orchestration. Give the steps, the compensations, the states, and where the money-losing risks are."

Reveal answer

Strong answer Requirements: no customer is charged for goods that do not ship; no goods ship unpaid; overselling by a unit is tolerable and compensated. Design: the orchestrator lives in the order service, with a saga_state row per order holding the current step, attempts, and deadline.

Steps, ordered so the hardest-to-reverse comes last:

  1. Create order in PENDING — compensation: mark CANCELLED.
  2. Reserve stock — compensation: release reservation.
  3. Charge card with the order id as idempotency key — compensation: refund.
  4. Create shipment — no compensation, because it is the pivot: once shipping accepts, the saga only moves forward, and any later failure is handled by retrying, not reversing.

Stock before payment is deliberate: releasing a reservation is cheap and invisible, while a refund is slow, visible, and costs card-processor fees. States per order: PENDING, STOCK_RESERVED, PAID, SHIPPING, COMPLETED, and on failure COMPENSATING and CANCELLED, plus NEEDS_ATTENTION when a compensation cannot succeed.

Every command carries the saga id and step number so replies can be matched and duplicates ignored. Timeouts per step — 30 seconds for payment, 5 minutes for shipping — after which the orchestrator queries the participant rather than assuming failure, because a timeout means unknown.

The money risk sits between steps 3 and 4: charged but not shipped, so that window has a dashboard and an alert.

Picture it the saga_state and outbox rows for order 123 at each step, including a crash between the charge and the shipment (Pattern: Saga Orchestration).

Make the invisible visible: the orchestrator's own table after every step.

saga_state over timeruns offline
# illustrative output
time      saga_state(order 123)                 outbox (commands)                 orders.status
10:00:00  step=RESERVE  attempts=1 dl=10:05     cmd c-1 ReserveStock  published   PENDING
10:00:01  step=CHARGE   attempts=1 dl=10:00:31  cmd c-2 ChargeCard    published   STOCK_RESERVED
10:00:03  step=SHIP     attempts=0 dl=10:05:03  cmd c-3 CreateShipment unpublished PAID
10:00:03  orchestrator crashes before relay publishes c-3
10:00:40  restart: row at SHIP, c-3 still unpublished -> relay publishes it            ✓
money window: PAID and no shipment, age 37 s -> on dashboard

The trace: a timeout is treated as unknown.

payment timeoutruns offline
10:00:01  ChargeCard c-2 sent (idempotency key = order id)
10:00:31  no reply: orchestrator queries payment -> "captured" -> advance to SHIP    ✓
          (assuming failure here would refund a charge that happened)                 ✗

Land it Order the steps so compensations get more expensive as you go and the irreversible one is last, then instrument the window where money has moved and goods have not.

Likely follow-ups
"The requirement changes: overselling is not tolerable, and payment must be authorised before stock is committed. Redesign the order."

I split payment into two steps, which most card processors support: authorise, which holds the funds without moving them and is cheap to void, and capture, which moves the money.

The order becomes: create order PENDING; authorise the card, compensation void; reserve stock with a strict, non-oversell reservation, compensation release; capture the payment — this is the pivot, because once money has moved the saga only goes forward; create shipment; confirm.

The authorisation gives the business confidence the customer can pay before any stock is touched, and its void is nearly free, so putting it before the reservation costs little.

The strict reservation is now the step most likely to fail, and it sits right before the pivot, so its compensation — releasing a hold — is trivial.

The money-risk window moves to between capture and shipment, which is the same window as before, and gets the same alert.

"Under time pressure, what do you cut from this design?"

I would cut the shipping step out of the saga entirely for the first release: the saga ends at PAID, and a separate, simple, retryable job creates shipments for paid orders, with an alert on paid orders older than an hour without a shipment.

That removes one participant, one compensation decision, and the longest timeout. I would also cut per-step timeouts down to a single saga-level deadline with one sweeper that queries every participant's status.

What I would not cut is the idempotency key on the charge, the release-stock compensation, and the NEEDS_ATTENTION state with a way for support to see it, because those three are the difference between a saga that loses money quietly and one that asks for help.

The state set can be smaller — PENDING, PAID, CANCELLED, NEEDS_ATTENTION — as long as the transitions are recorded with timestamps so the fuller states can be reconstructed later.

"What exactly is on the dashboard for the charged-but-not-shipped window?"

A count of orders in PAID by age bucket — under 5 minutes, 5 to 30, 30 to 60, over an hour — with the sum of money in each bucket, because the business cares about the amount as much as the count.

PAID age bucketsruns offline
# illustrative output
bucket        orders   amount
< 5 min          41    12,300
5-30 min          3       900
30-60 min         0         0
> 1 h             0         0       page if oldest PAID > 30 min

A line of the oldest PAID order's age over time, which is the one that pages: above 30 minutes for a single order, or above 5 minutes for more than fifty orders, someone looks.

A table of the twenty oldest, with order id, amount, the last command sent, its attempt count, and a link to the participant's status for that command.

And the rate of transitions out of PAID into SHIPPING per minute, so a stall shows as that line dropping to zero before the age buckets fill.

The same layout exists for the COMPENSATING state, because a refund that is not completing is the same kind of window in the other direction.

"Why not a shipping compensation — cancel the shipment?"

Because the shipment step's failure modes do not need it, and offering it invites the wrong design. Once shipping has accepted the request, what can fail afterward?

The carrier may be late, the label may need regenerating, the warehouse may be out of the item after all — but none of those are reasons to refund the customer and cancel the order automatically; they are reasons to retry, re-route, or ask a human.

If I gave the saga a "cancel shipment" compensation, a transient failure in a later step would trigger it, and the customer would get a refund for an order that could have shipped an hour later.

So the shipment step is the pivot: it can fail before acceptance and then the earlier steps compensate; after acceptance, failures are handled by forward recovery.

A cancellation that comes from the customer after this point is a separate return process, with its own rules, not a saga compensation.

Q54 · Scenario. "It is 02:00. Three hundred orders are stuck in PAID for the last four hours; none have moved to SHIPPING. Nothing is alerting. Walk me through the next thirty minutes."

Reveal answer

The real test Whether you can find where a saga stopped and choose between resuming, compensating, and waiting — while keeping customers from being charged for nothing.

Strong answer The symptom is a saga stalled at one boundary: the step after PAID, which is "create shipment", is not completing.

Evidence, in order:

  1. Is the orchestrator issuing the shipping command? Check its outbox and the command topic's producer metrics.
  2. Is shipping consuming? Check consumer lag on that topic, its error logs, and its dead-letter topic.
  3. Are replies coming back and being ignored? Check the reply topic's lag on the orchestrator side.

Causes ranked:

  1. The shipping consumer is down or crash-looping on a poison message, and everything behind it waits.
  2. The orchestrator's poller stopped after a deploy and commands are sitting unpublished in its outbox.
  3. A schema change made the reply unreadable, so the orchestrator never advances.

Fix: restart or repair whichever side is stuck, then let the saga resume — the orchestrator's timeout handling should query shipping for each stuck order's status rather than re-sending blindly, because some shipments may have been created and the reply lost.

Only if shipping cannot be repaired within the business's promise window do I start compensating — refund and cancel — and I would decide that with the business owner, not alone.

Prevention is the missing alert: a saga age metric per state with a threshold, and a dead-letter alert, so a four-hour stall is a ten-minute page.

Picture it the consumer lag, the outbox and the saga_state rows that show where order 123 and its 299 neighbours stopped (Pattern: Dead Letter Queue and Pattern: Outbox).

Make the invisible visible: three checks, one per side of the boundary.

three checksruns offline
# illustrative output
1) orchestrator outbox        SELECT count(*) FROM outbox WHERE topic='shipping.cmd' AND published=false  -> 0     ✓ commands left
2) shipping consumer group    kafka-consumer-groups --describe --group shipping
   GROUP     TOPIC         PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG  CONSUMER-ID
   shipping  shipping.cmd  0          5120            5421            301  (none/crash-looping)   ✗
3) saga_state                 SELECT status, count(*), min(updated) FROM saga_state GROUP BY status
   PAID   300   22:03        <- oldest 4 h ago, nothing alerting

The trace: one poison record holds back everything behind it in the partition.

partition 0 of shipping.cmdruns offline
offset 5119  CreateShipment(order 90)    consumed ✓
offset 5120  CreateShipment(order 91)    deserialisation error, retried forever   ✗ poison
offset 5121..5421  orders 92..392        waiting behind 5120
fix: move 5120 to shipping.cmd.DLT or reset offset to 5121 (consumer stopped), record order 91  ✓
lag 301 -> 0, 300 sagas advance

Land it A stuck saga is found by asking which side of one boundary is silent, and the first fix is to resume, never to compensate on a guess.

Likely follow-ups
"You restarted the shipping consumer and it crashed again immediately on the same message. What now?"

That is a poison message at the head of a partition, and the three hundred orders are queued behind it.

I would read the record — the consumer's log names the offset and the exception — and decide in a minute whether it is a data problem or a code problem.

If it is one bad record, I skip it: move it to the dead-letter topic by hand, or set the group's offset for that partition past it with kafka-consumer-groups --reset-offsets --to-offset while the consumer is stopped, and record the skipped order for follow-up.

The consumer then drains the backlog.

If it is a code problem — a deploy introduced a deserialisation failure for a new event version — every record will fail, and the fix is a rollback of the shipping service to the previous version, which takes minutes and unblocks everything.

Either way, the error handler that let one message block the partition for four hours is a bug to fix afterwards: bounded retries, then dead-letter.

"Why not just re-send the shipping command for all three hundred?"

Because some of the shipments may already exist.

blind re-send versus queryruns offline
# illustrative output
order 92  shipment exists (reply lost)   blind re-send -> second shipment, two parcels   ✗
order 92  GET /shipments?order=92 -> found -> advance saga manually                      ✓
order 93  GET /shipments?order=93 -> none  -> re-send command c-93 (same command id)     ✓ idempotent guard

If shipping consumed a command, created the shipment, and then failed before publishing its reply — or the reply is sitting on a topic the orchestrator is not consuming — a blind re-send creates a second shipment for the same order, and the customer receives two parcels.

The safe procedure is to query: for each stuck order, ask shipping's status endpoint whether a shipment exists for that order id.

Orders with a shipment get their saga advanced manually or by a replayed reply; orders without one get the command re-sent with the original command id, which shipping's idempotency guard also protects.

If the commands are idempotent on the order id and shipping is known to enforce that, a re-send is safe and the query step can be skipped — but I would verify that guarantee in the code before relying on it at 02:00, not assume it.

"Nothing was alerting. What are the exact alerts you would add, with thresholds?"

Four. Saga age per state: a gauge of the oldest saga in each non-terminal state, alerting when PAID exceeds 15 minutes for any order or 5 minutes for more than twenty — the numbers come from the business's promise.

Transition rate: sagas leaving PAID per minute compared with sagas entering it over the last hour, alerting when the outflow drops below a quarter of the inflow for ten minutes, which catches a stall before ages grow.

Consumer health for every participant: lag on each command topic over a threshold in seconds, and any consumer group with zero active members. Dead-letter topics: alert on the first message, not a count.

All four go to the on-call rotation with a runbook link, and the saga-age one is the most important because it is independent of the mechanism — whatever stops the saga, the age grows.

The dashboard from the design question is the page the alert links to.

"When exactly would you decide to compensate rather than wait, and who decides?"

The decision is about the promise to the customer and the cost of each path, and it is not mine alone at 02:00.

If shipping can be repaired within the window the business has promised — same-day dispatch, next-morning cut-off — I wait and resume, because resuming gives the customer what they paid for.

If the repair estimate is beyond that, I call the business owner on the escalation list, present the two options with numbers — three hundred orders, this amount of money, a refund that takes days to appear on statements versus a shipment that is a day late — and they choose.

In most retail cases the answer is to wait and communicate: send the customers a delay notice and ship when repaired. Compensating is right when the goods can no longer be supplied or the delay is beyond what a customer would accept.

The runbook should name the person who decides, so the engineer is not making a refund decision alone.

Q55. "Sagas give up isolation. What anomalies does that let in, and what countermeasures do you know?"

Reveal answer

Strong answer Because each step commits locally, other transactions can see and act on a saga's intermediate state, which brings back anomalies the database used to prevent.

Three anomalies come back:

  • Dirty read across the saga: a report counts an order as PAID that will be refunded a second later.
  • Lost update: a cancel request arrives between the reserve and the charge, updates the order, and is then overwritten when the saga advances.
  • Non-repeatable read: two steps of the same saga see different stock levels because another saga changed them in between.

The countermeasures:

  1. Semantic lock: the saga marks records as in-flight — a PENDING status is exactly that — and other operations check the flag and either wait, reject, or queue.
  2. Commutative updates: design operations so order does not matter, such as reserving stock by decrementing rather than by setting a value.
  3. Pessimistic view: order the steps so the anomaly's window is short — charge last, or reserve before charging.
  4. Re-read before write: each step re-reads the current state rather than trusting the value it saw earlier.
  5. Version check: commands carry the version of the record they were computed from, and the participant rejects stale ones.

Most systems use the PENDING flag plus a version check and accept the rest.

Picture it the lost update on order 123 with the order row and its version at every step, and the version check that turns it into a conflict (Pattern: Saga Orchestration).

Make the invisible visible: a thread picture, one column per actor, with the order row after each step.

cancel races the sagaruns offline
# illustrative output
step  Saga (orchestrator)                  Cancel request                  orders row
 1    read order v7 (PENDING)                                              123 PENDING      v7
 2                                           UPDATE ... SET CANCELLED       123 CANCELLED    v8
 3    charge card ok, advance:
      blind UPDATE SET PAID                                                123 PAID         v9   ✗ cancel lost
 3'   advance with WHERE version=7           -> 0 rows updated                123 CANCELLED    v8   ✓ conflict
      orchestrator re-reads, sees CANCELLED, starts refund compensation

The fix: the optimistic update and the semantic lock.

guarded updateruns offline
UPDATE orders SET status='PAID', version=8 WHERE id=123 AND version=7;   -- Result: 0 rows = conflict, re-read
-- Cancel while PENDING: routed to the saga as a signal, not written to the order  ✓ semantic lock

Land it A PENDING status is a semantic lock, and treating it as one — every other operation must respect it — is most of saga isolation in practice.

Likely follow-ups
"Show me the version check concretely — what does the command carry and what does the participant do?"

Every aggregate row has an integer version that increments on each update. When the orchestrator reads the order at version 7 and decides to send "charge card for order 123", the command includes expectedVersion: 7.

Payment does not check the order's version — it does not own the order — but when the orchestrator receives the reply and goes to advance the order, it updates with WHERE id = 123 AND version = 7 and sets version to 8; if zero rows are affected, something else changed the order in the meantime — a cancel — and the orchestrator re-reads and re-decides rather than blindly advancing.

For participants that own the record the command touches, such as inventory with a reservation, the same pattern applies inside them: the command carries the reservation version it was computed from, and a stale command is rejected with a specific reply the orchestrator handles.

It is optimistic locking across a saga: cheap, and it turns a lost update into an explicit conflict.

"What does a commutative update look like for stock, and what is the trap?"

Commutative means the result is the same whichever order the operations arrive in.

commutative but not idempotentruns offline
# illustrative output: UPDATE stock SET available=available-3 WHERE sku='X' AND available>=3
available=10   reserve 3 (event e-1)  -> 7   ✓
available=7    reserve 2 (event e-2)  -> 5   ✓  same final value in either order
available=5    e-1 redelivered        -> 2   ✗ double reservation, so add guard on event id

For stock, UPDATE stock SET available = available - 3 WHERE sku = 'X' AND available >= 3 is commutative with other decrements and increments: two reservations of 3 and 2 give the same final number in either order, and the guard prevents going negative.

The non-commutative version is "read available, compute new value, write it", which loses one of two concurrent updates.

The trap is idempotency: a commutative decrement applied twice because of a redelivered message is a double reservation, so the operation still needs the guard table keyed by event id, or a reservation row keyed by order id whose insert fails on the second attempt.

Commutativity solves ordering between different operations; it does not solve repetition of the same one. Both are needed, and confusing them is how "we made it commutative" turns into a stock discrepancy.

"How does a semantic lock affect the other operations — what does a report or a cancel do when it sees PENDING?"

Each operation gets an explicit policy for in-flight records. A report either excludes PENDING orders or shows them in their own column, so revenue is not counted for orders that may compensate — the finance team decides which.

A cancel request routes to the saga as a signal rather than writing to the order, as in the concurrent-cancel scenario.

A customer-service edit — changing the address — is either refused with "order is being processed, try in a moment" or queued to apply after the saga completes.

A second checkout for the same cart is rejected because the cart is already attached to a PENDING order.

The mechanical implementation is a check on status at the start of each operation and a version check at the end; the design work is the list of operations and the decision for each, which I write down as a table. The semantic lock is only a lock if everyone honours it.

Q56 · Scenario. "A saga is compensating: the refund step has failed 40 times over two days because the card processor says the original charge id is unknown. The order is stuck in COMPENSATING. What now?"

Reveal answer

Strong answer The symptom is a compensation that cannot succeed by retrying, which means the retry policy has become a way of not deciding.

Evidence: payment's own record of the charge — was it ever confirmed by the processor, or was it a PENDING charge whose confirmation was lost — and the processor's dashboard for that customer.

Causes ranked:

  1. The original charge never actually settled, so there is nothing to refund and the saga's state is wrong rather than the processor.
  2. The charge id stored by payment is the pre-authorisation id, not the capture id the processor expects.
  3. The processor's retention window has passed.

The fix for this order is manual: a support engineer verifies with the processor whether money moved and either marks the compensation done (nothing to refund) or issues a manual refund, then advances the saga to CANCELLED through an administrative endpoint that records who did it and why.

The design fix is that compensations must have a bounded retry policy — say ten attempts with backoff over an hour — after which the saga moves to NEEDS_ATTENTION, raises a ticket with the full context, and stops consuming resources.

Prevention: a permanent-failure classification for compensations, an owner for the attention queue, and a nightly reconciliation between payment's ledger and the processor's.

Picture it the refund attempts and the saga row over two days, with an unbounded retry versus a bounded retry that ends in NEEDS_ATTENTION (Pattern: Saga Orchestration).

The trace: a refund the processor will never accept, retried on a fixed schedule.

unbounded retryruns offline
# illustrative output
attempt  time        reply                       saga_state
   1     10:00       REJECTED CHARGE_NOT_FOUND   COMPENSATING attempts=1
   2     10:05       REJECTED CHARGE_NOT_FOUND   COMPENSATING attempts=2
  ...                                            ...
  40     +2 days     REJECTED CHARGE_NOT_FOUND   COMPENSATING attempts=40   ✗ nobody told

The fix: a bounded retry and an attention queue.

bounded retryruns offline
attempt  delay   reply        saga_state
   1     0 s     RETRY        COMPENSATING
   2     30 s    RETRY        COMPENSATING
  ...   backoff, ten attempts over about an hour
 REJECTED CHARGE_NOT_FOUND -> NEEDS_ATTENTION immediately   ✓
saga_attention: (s-9, order 123, REFUND, last_error=CHARGE_NOT_FOUND, attempts=1, assigned_to=NULL)
ticket opened at 10:00, not forty failures over two days

Land it Retry forever is not a strategy; a compensation that fails permanently needs a human path designed on day one.

Likely follow-ups
"The support engineer marks it done, and next week the customer disputes the charge. What went wrong in the process?"

The manual resolution was made on the wrong evidence.

"Charge id unknown" from the processor was taken to mean "no money moved", but a charge can exist under a different id than the one stored — the authorisation id versus the capture id — or under a different merchant account after a configuration change.

The process fix is that a manual close of a compensation requires a positive confirmation from the processor's own records, searched by customer, amount, and date rather than by the id we hold, and that confirmation is attached to the administrative action.

It also means the administrative endpoint should offer two outcomes, "verified no charge" and "manually refunded", each requiring a reference, and no free-text "resolved".

And the nightly reconciliation between payment's ledger and the processor's settlement report would have found a settled charge with no matching refund before the dispute arrived, which is why the reconciliation is part of the design and not an afterthought.

"What does the NEEDS_ATTENTION queue look like, and who owns it?"

It is a table, not a topic: saga_attention(saga_id, order_id, state, step, last_error, attempts, first_failed_at, assigned_to, resolution, resolved_at), with a small internal screen that lists open items oldest first and shows the saga's full history alongside.

saga_attention rowsruns offline
# illustrative output
saga_id  order  step    last_error          attempts  first_failed_at  assigned_to  resolution
s-9      123    REFUND  CHARGE_NOT_FOUND    1         10:00            maya         (open)
s-4      88     SHIP    ADDRESS_UNDELIVERABLE 1       09:12            -            (open, oldest 4 h)

Each row has a category — refund failed, participant unreachable, data mismatch — and a runbook link per category.

The owner is the team that owns the saga, with a daily rota so it is someone's job that day, and a service-level target such as "every item touched within four hours, resolved within two business days".

A metric of open items and oldest age feeds an alert that goes to the team lead, not the on-call engineer, because these are not outages. The resolution actions are buttons that call the administrative endpoints, so every resolution is recorded with who and why.

What makes it work is the rota; a queue without a person is a dead-letter topic with a nicer interface.

"How do you classify a compensation failure as permanent versus transient in code?"

By the participant's reply, which must be designed to say so.

A refund command's reply has a status of DONE, RETRY, or REJECTED with a reason code, and the orchestrator's policy is driven by that: RETRY follows the backoff schedule up to the limit; REJECTED with a reason such as CHARGE_NOT_FOUND or ALREADY_REFUNDED goes to NEEDS_ATTENTION immediately, or in the already-refunded case marks the step done.

A timeout with no reply is transient by default. What I avoid is inferring permanence from an exception class thrown by an HTTP client, because that conflates "the processor said no" with "the network dropped".

The payment service, which talks to the processor, is the one place that knows the processor's error codes, so it does the mapping and the orchestrator only sees the three statuses. The classification is tested with one unit test per reason code.

"Could the design have avoided this failure entirely?"

Mostly, with two changes.

First, the refund command should carry enough to succeed without the exact charge id: the order reference, the amount, and the customer, so payment can find the charge by reference if the stored id is stale — many processors support a lookup by merchant reference.

Second, the saga should record the processor's capture id as part of the charge step's reply and use that, not the authorisation id, for the refund; the scenario's "pre-authorisation id" cause is a data-modelling mistake in the charge step's reply.

Beyond those, the retry limit and the attention queue are what turn the remaining rare cases into a ticket within an hour instead of forty failures over two days.

I would not claim every case can be avoided — processors have retention windows and outages — which is why the human path is designed on day one rather than discovered in an incident.

Q57. "What is the pivot transaction in a saga, and how does it change the order you put steps in?"

Reveal answer

Strong answer Saga steps come in two kinds:

  • Compensable steps can be undone by a compensating action — a reservation can be released, a charge refunded.
  • Retryable steps cannot fail permanently, only be delayed — writing a row in your own database, appending to a log — so you retry them until they succeed and never need to reverse them.

The pivot is the boundary between them: the last step that can fail and that, once it succeeds, commits the saga to completing.

  • Before the pivot: any failure means compensating everything so far.
  • After the pivot: any failure means retrying until done, and no compensation runs.

This decides the order. All compensable steps go before the pivot, arranged so the most expensive compensation is nearest to it, and everything after the pivot is retryable only.

In the checkout: reserve stock (cheap to undo), then charge the card (expensive to undo), then the pivot — say, confirm the order — then the retryable tail: create shipment, send confirmation, update the search index.

Put an irreversible action such as shipping a parcel before the pivot and you have designed a saga that can charge back money it can never recover; put a failing-prone action after the pivot and you have designed one that can hang forever.

Most saga bugs in practice are steps on the wrong side of this line.

Picture it the checkout steps laid out around the pivot, and the table rows after a failure on each side of it (Pattern: Saga Orchestration).

Make the invisible visible: steps in order, with their kind.

step order around the pivotruns offline
1 reserve stock     compensable  (release)       ┐ before the pivot:
2 charge card       compensable  (refund, costly) ┘ failure => compensate back
3 confirm order     PIVOT                           
4 create shipment   retryable                      ┐ after the pivot:
5 send confirmation retryable                      │ failure => retry, never reverse
6 update search     retryable                      ┘

The trace: a failure on each side of the pivot.

failure before versus afterruns offline
# illustrative output
fail at step 2 (card declined): orders 123 CANCELLED, stock reservation released   ✓ compensated
fail at step 5 (mail down):     orders 123 CONFIRMED, saga_state step=NOTIFY attempts=6 -> retried until sent   ✓
wrong side: ship (step 4 before pivot), then charge fails ->
            parcel gone, nothing to compensate                                       ✗

Land it Everything before the pivot must be undoable and everything after it must be unfailable, and I place each step by asking which of those it is.

Likely follow-ups
"What if a step after the pivot fails permanently — the shipping service rejects the address as undeliverable?"

Then the assumption that the step was retryable was wrong, and the saga needs a human path rather than an automatic reversal.

permanent failure after the pivotruns offline
# illustrative output
saga_state  step=SHIP  status=NEEDS_ATTENTION  reason=ADDRESS_UNDELIVERABLE  orders 123 stays PAID
customer-service task created -> address corrected -> shipping step re-issued   ✓

After the pivot, the customer has paid and the business has committed; a permanent failure there is not a reason to unwind the whole order automatically, because the right resolution is usually to fix the input — contact the customer for a corrected address — and continue.

So the orchestrator moves the saga to NEEDS_ATTENTION with the reason, the order stays PAID, a customer-service task is created, and when the address is corrected the shipping step is re-issued.

If the customer cannot be reached within the business's limit, a human triggers a cancellation, which is a separate flow: refund and close. The design lesson is that "retryable" means "no automatic compensation", not "cannot fail"; the failure just has a different owner.

Validation that could have caught the address should also move before the pivot.

"Can a saga have more than one pivot, or none?"

Exactly one by definition, though it can be at either end.

If every step is compensable — reserve, authorise, and nothing irreversible until a final confirm — the pivot is the last step, and the saga can fully unwind at any point before it; that is the safest shape and the one I aim for.

If the first step is already irreversible — a saga that starts by sending a legally required notification — the pivot is the first step, which means nothing before it can fail, and everything after it must be forward-recoverable; that is a fragile shape and usually a sign the notification should be moved later.

A saga with no pivot would be one where every step is retryable and nothing is ever compensated, which is a pipeline rather than a saga.

Where I see two apparent pivots, the second is really a step that should be made compensable or the saga should be split into two sagas with a handover state between them.

"How do you decide where the pivot goes when the business wants shipping before payment capture?"

The business is asking to move an irreversible action — dispatching goods — before the money moves, which puts the pivot at shipping and makes the capture a post-pivot retryable step.

The consequence they must accept: a capture that fails permanently — card cancelled between authorisation and capture — leaves goods shipped and unpaid, and the recovery is a dunning process, not a compensation.

That is acceptable in some businesses, such as invoice-based B2B, and unacceptable in consumer retail.

So I make the trade explicit with the numbers: authorisation typically holds for seven days, capture failure rates after a successful authorisation are a fraction of a per cent, and the expected loss is that fraction of shipped value.

If the business accepts it, the design is authorise, reserve, ship (pivot), capture (retryable, with an alert on failure), notify. If not, capture moves before shipping and the pivot with it.

Q58 · Design. "Design the persistence and recovery of a saga orchestrator so that a crash at any instant leaves the saga resumable. Include the table, the loop, timeouts, and duplicate replies."

Reveal answer

Strong answer Requirements: the orchestrator may crash between any two actions; replies may arrive twice or out of order; the saga must resume within a minute of restart. Design: a table saga(id, type, state, current_step, step_attempts, last_command_id, deadline_at, version, updated_at) plus the orchestrator's outbox.

The loop is one transaction per transition:

  1. Read: load the saga row with its version.
  2. Decide: pick the next command.
  3. Write: insert the command into the outbox.
  4. Advance: update the state, set a deadline, bump the version, and commit.

So the state change and the command are atomic, and the relay delivers the command at least once.

Replies arrive on a topic; the handler is idempotent: each reply carries the saga id and the command id it answers, and a reply whose command id does not match last_command_id is logged and dropped as stale or duplicate.

A recovery sweeper runs every 30 seconds and selects sagas whose deadline_at has passed, with FOR UPDATE SKIP LOCKED. For each overdue saga it does one of two things:

  • Retryable step: re-issue the last command with the same command id.
  • Compensable step: query the participant's status endpoint before deciding.

Each pass increments the attempt count, and a limit moves the saga to NEEDS_ATTENTION. The sweeper and the reply handler can race, so both use the version column: one wins and the other retries.

Trade-off: the design is a small state machine with a lot of ceremony; the alternative is a workflow engine such as Temporal, which is what I would choose above a handful of saga types.

Picture it One saga row and one outbox row for order 123, shown before and after a transition and at each crash point (see the orchestration pattern and the outbox).

The setup: the saga table sits in the same database as the orchestrator's outbox, so one local transaction can touch both.

saga tableruns offline
CREATE TABLE saga (
  id uuid PRIMARY KEY, type text, state text, current_step text,
  step_attempts int, last_command_id bigint, deadline_at timestamptz,
  version int, updated_at timestamptz);
-- outbox(id, aggregate_id, event_type, payload, published_at) is in the same database

Make the invisible visible: the rows of both tables just before and just after the commit of one transition.

table stateruns offline
BEFORE the transition (PaymentReserved reply for command 41 arrives)
 saga:   9a1 | CHARGE_CARD | last_command_id=41 | version=6 | deadline 10:01:30
 outbox: (no row for 42)

AFTER the single COMMIT
 saga:   9a1 | RESERVE_STOCK | last_command_id=42 | version=7 | deadline 10:03:01
 outbox: id=42 | topic=inventory.commands | key=order-123 | published_at=NULL

The trace: kill the orchestrator at each instant and see what the next start finds.

crash pointsruns offline
1. read saga 9a1 (v6)                         crash -> ✓ nothing changed, redelivered reply is handled again
2. BEGIN; INSERT outbox 42; UPDATE saga v6->v7   crash -> ✓ rollback, neither row exists
3. COMMIT                                      crash -> ✓ saga v7 and outbox 42 both exist
4. relay publishes 42 to the broker            crash -> ✓ row still unpublished, relay sends it on restart
5. reply for 42 arrives twice                  2nd copy: last_command_id is now 43 -> ✓ dropped as stale

What you see: the orchestrator log around a crash at step 3.

consoleruns offline
# illustrative output
10:02:01.114 saga=9a1 step=RESERVE_STOCK cmd=42 committed v6->v7 deadline=10:03:01
10:02:01.115 (orchestrator process killed)
10:02:09.870 relay  published outbox id=42 topic=inventory.commands (8 s late)
10:02:10.402 reply  saga=9a1 cmd=42 matches last_command_id -> advance v7->v8
10:02:10.980 reply  saga=9a1 cmd=42 stale (last_command_id=43) -> dropped

Why: the only state that exists is what committed, and the saga row and the command commit together, so there is no instant at which one exists without the other.

Land it The saga row, the outbox command, and the version check commit together, so a crash at any instant either happened before the transition or after it, never in between.

Likely follow-ups
"Walk me through a crash between committing the state row and the relay publishing the command. What happens on restart?"

Nothing is lost, because the command was written to the outbox in the same transaction as the state row. On restart the relay finds the unpublished outbox row and publishes it, and the participant receives it — a few seconds late.

The saga row already says "waiting for reply to command 42", with a deadline, so when the reply arrives the handler matches last_command_id and advances.

If the restart takes longer than the step's deadline, the sweeper fires first. It sees the saga is overdue and re-issues command 42 with the same id.

The participant may then receive command 42 twice: once from the relay's delayed publish and once from the sweeper. Its idempotency guard makes the second a no-op.

message timelineruns offline
# illustrative output
10:02:01  saga 9a1 committed, outbox 42 unpublished
10:03:01  sweeper: deadline passed -> re-issue cmd 42 (same id), attempts=1, deadline +120 s
10:03:02  inventory receives cmd 42      -> processed_messages: insert 42 ✓ reserve stock
10:03:40  relay restarts, publishes 42   -> inventory receives cmd 42 again
10:03:40  inventory: insert 42 hits primary key -> ✓ replies with stored result, no second reservation

The one thing I check in the design is that the sweeper reuses the command id rather than minting a new one, because a new id would let the participant execute the step twice.

"Two replies to the same command arrive, one on each of two orchestrator instances. What happens?"

Both handlers read the saga row, both see last_command_id = 42 matching, both decide the same next transition, and both try to commit an update with WHERE version = 7.

One wins and sets version 8, writes the next command to the outbox, and commits.

The other's update affects zero rows, so it rolls back and its outbox row is not written.

two instances racingruns offline
# illustrative output
A: UPDATE saga SET version=8, last_command_id=43 WHERE id='9a1' AND version=7  -> 1 row  (outbox 43 written)
B: UPDATE saga SET version=8, last_command_id=43 WHERE id='9a1' AND version=7  -> 0 rows (rollback, no outbox 43)
B: re-read saga: last_command_id=43, reply is for 42 -> ✓ stale, dropped

The loser either retries — re-reads the saga, finds last_command_id is now 43, recognises the reply as stale, and drops it — or simply logs and moves on, depending on how the handler is written; I write it to re-read once and then drop.

So the version column is doing two jobs: it serialises concurrent handlers, and combined with the command id it makes duplicate replies harmless.

Without it, both instances would write the next command and the participant would get it twice, which its guard would catch, but the state row could end up with a step counted twice.

"What are the timeout values per step, and how does the sweeper avoid acting too early?"

The deadline is the step's expected p99 plus generous margin plus the delivery latency of the outbox and the reply path, because the sweeper acting early is the expensive mistake — it re-issues commands and, for compensable steps, makes status queries that would have been unnecessary.

For a card charge with a processor p99 of 3 seconds, a deadline of 60 seconds; for shipment creation, 10 minutes; for a compensation, longer still, because compensations run in degraded conditions.

The sweeper runs every 30 seconds, so the effective delay is the deadline plus up to 30 seconds.

When it acts, it increments step_attempts and extends the deadline with backoff, so a slow participant is not hammered:

deadline backoffruns offline
attempt 0: deadline = created + 60 s
attempt 1: deadline = now + 120 s
attempt 2: deadline = now + 240 s
attempt 10 (limit): state = NEEDS_ATTENTION, a human is paged

The attempt limit, perhaps ten, sends the saga to NEEDS_ATTENTION. These values live in configuration per saga type and step, not in code, and they are revisited when the participant's latency metrics change.

"How do you stop the sweeper and the reply handler from starving each other under load?"

The sweeper's FOR UPDATE SKIP LOCKED prevents contention among sweeper instances.

Between the sweeper and the reply handler the version check resolves conflicts. Under heavy load a reply handler that keeps losing the race would retry repeatedly, so there are two mitigations.

The sweeper takes small batches — fifty sagas — and holds the row lock only for the duration of one transaction, milliseconds, so a reply handler's optimistic update rarely collides.

And the sweeper only selects sagas whose deadline has passed, which in a healthy system is a handful, so the overlap with live replies is tiny; if the overlap is large, the deadlines are too short or the participants are slow, and either is a signal on the dashboard.

I have not needed a queue between them; the database's row locking and a short sweeper transaction are enough, provided the sweeper never does network calls while holding the lock — it reads, decides, writes the outbox row, commits, and only then anything slow happens via the relay.

Q59. "What does a durable workflow engine such as Temporal give you that a hand-written orchestrator does not, and what does it cost?"

Reveal answer

Strong answer A durable workflow engine lets you write the saga as ordinary sequential code — call charge, await the result, call reserve, on exception call refund — and makes that code survive crashes.

It does this by recording every step's inputs and results in an event history; when a worker crashes, another worker replays the history to rebuild the code's position and continues from the next step, so the developer never writes a state table, a recovery sweeper, or a deadline handler.

Temporal (and its ancestor Cadence) is the widely used option as of 2026; it also gives built-in retries with backoff per activity, timers that survive for days, signals for human approval steps, and a UI that shows exactly where each workflow is.

The costs are three:

  • Infrastructure: a server cluster and a database, or a paid cloud, and someone must own it.
  • Determinism: workflow code is replayed, so it may not use random numbers, clock reads, or direct I/O outside activities, and that rule surprises every new team.
  • Versioning: changing a workflow while thousands of instances are mid-flight needs care.

I would reach for it when a platform has more than a few saga types, when sagas run for days, or when human steps are involved; for one three-step saga a persisted state machine is cheaper.

Picture it The event history the engine keeps for order 123, and how a second worker rebuilds the code's position from it after a crash (compare the hand-written orchestration pattern).

The setup: the saga as ordinary sequential code, with each remote call made through an activity.

CheckoutWorkflow.javaruns offline
public void checkout(Order o) {
    String chargeId = payment.charge(o);       // activity: recorded once
    try {
        inventory.reserve(o);                  // activity
        shipping.create(o);                    // activity
    } catch (ActivityFailure e) {
        payment.refund(chargeId);              // ✅ compensation is just a catch block
        throw e;
    }
}

Make the invisible visible: the engine stores one history row per step, in place of the saga table you would have written.

event history (order 123)runs offline
# illustrative output
#  type                  detail
1  WorkflowStarted       order 123
2  ActivityScheduled     charge
3  ActivityCompleted     chargeId=ch_77
4  ActivityScheduled     reserve
5  ActivityCompleted     ok
6  ActivityScheduled     shipping.create     <- worker A is killed here

The trace: worker B picks the workflow up and replays the code against that history.

replay on worker Bruns offline
run checkout() from the top
 payment.charge(o)     history #3 has the result -> ✓ returns ch_77, no second charge
 inventory.reserve(o)  history #5 has the result -> ✓ returns ok, no second reservation
 shipping.create(o)    history #6 scheduled, no result -> ✓ waits for / reschedules the activity
 (code position rebuilt; no state table, no sweeper, no deadline handler written by us)

Why: completed activities are answered from the recorded history instead of being run again, so the code reaches its old position without repeating any side effect.

Land it The engine sells you back the ability to write a saga as a function, and the price is running the engine and writing deterministic code.

Likely follow-ups
"Explain the determinism rule with an example of code that breaks it, and how it fails."

Workflow code is replayed from the event history to rebuild its position, so every decision it makes must come out the same on replay.

Code that breaks it: if (Instant.now().getHour() < 12) chargeNow(); else scheduleForTomorrow();

On the first run at 11:00 it charged. On replay at 14:00 the code takes the other branch, which does not match the recorded history. The engine raises a non-determinism error and the workflow is stuck.

replay mismatchruns offline
# illustrative output
history #2  ActivityScheduled chargeNow         (recorded at 11:00)
replay 14:00: code takes else-branch -> wants scheduleForTomorrow
  ❌ TRAP: recorded command differs from the command the code produced
  Result: non-determinism error, the workflow task fails and the workflow is stuck
  ✅ FIX: use the engine's clock (Workflow.currentTimeMillis()) so replay sees the recorded time

Same for reading a random number, a configuration value that changed, or an environment variable, or calling a service directly instead of through an activity.

The correct version uses the engine's own time — Workflow.currentTimeMillis() in Temporal's Java SDK — which is recorded in the history and replayed identically, and it puts every side effect in an activity, whose result is recorded once and replayed from the record.

The surprising cases are libraries: a map with non-deterministic iteration order inside workflow code can break replay.

"How do you change a workflow's code while thousands of instances are mid-flight?"

With versioning inside the workflow code, because existing instances will replay the old history against the new code.

Temporal's approach is a version marker: int v = Workflow.getVersion("add-fraud-check", DEFAULT_VERSION, 1).

The first time a workflow reaches that line it records the version it used. Old instances replay with the old branch and new instances take the new one.

versioned branchruns offline
int v = Workflow.getVersion("add-fraud-check", Workflow.DEFAULT_VERSION, 1);
if (v == 1) {
    fraud.check(o);          // new instances only
}                            // old instances skip it on replay: ✓ history still matches
payment.charge(o);

The code keeps both branches until every instance started before the change has completed, which can be days for long-running sagas, and then the old branch is removed.

The alternative is worker versioning, where old workers keep running the old code for old instances and new workers take new ones, which Temporal supports through build ids.

Either way, a change to workflow code is a deliberate operation with a check — Temporal's replay test runs recorded histories against the new code in CI and fails on non-determinism — rather than an ordinary deploy.

"When is the hand-written orchestrator the right choice despite the engine's advantages?"

When the platform has one or two saga types, they are short — minutes, not days — and there is nobody to own an engine.

A persisted state machine is a table, a sweeper, and a few hundred lines of code, and it runs on infrastructure the service already has.

Adding Temporal means a cluster with its own database and upgrade cadence, or a paid cloud service and a network dependency on it for every step, plus the determinism rules that every engineer on the team must learn.

For a checkout saga in a team of six with no other workflows, that is more machinery than the problem.

The crossover in my experience is around three or four saga types, or the first saga that waits for a human or runs for days, because those are the cases where timers and signals are painful to hand-write.

I would also lean to the engine earlier if the organisation already runs one for another team.

"What does the engine cost at runtime — where is the latency?"

Every step is a round trip through the engine's persistence.

Starting an activity means the worker records the scheduling event, the engine persists it, an activity worker polls and picks it up, runs it, reports the result, the engine persists that, and the workflow worker is woken to continue.

Each of those is a database write and a poll, so a step adds on the order of tens of milliseconds even when the activity itself is instant.

A saga of six steps adds perhaps 100 to 300 milliseconds over a hand-written orchestrator that writes one row per step.

latency arithmeticruns offline
# illustrative numbers
engine, per step: persist schedule 10 ms + poll/pickup 10 ms + persist result 10 ms + wake workflow 10 ms = ~40 ms
engine, 6 steps:  6 x 40 ms = ~240 ms
hand-written, 6 steps: 6 x one row write (~5 ms) = ~30 ms
difference: ~210 ms, inside the 100 to 300 ms range

Throughput is bounded by the engine's database; Temporal scales it by sharding, and a self-hosted cluster needs tuning to handle thousands of workflow starts a second. History size also grows with each step and signal, and a very long workflow needs continue-as-new to reset it.

For a checkout saga these costs are fine; for a high-frequency, low-latency pipeline they are the reason to use something else.

Q60 · Scenario. "A customer clicked 'cancel' two seconds after placing an order. The checkout saga was mid-way through charging the card. The order ended up CANCELLED and the card charged, and no refund ever happened. How?"

Reveal answer

Strong answer Two operations on one order ran at the same time with no coordination between them: the checkout saga and a cancel request. Evidence: the order's state history with timestamps, and whether the cancel handler checked the saga's state before writing.

The likely sequence:

  1. Cancel: the handler saw the order in PENDING, set it to CANCELLED directly, and returned.
  2. Reply: the saga then received PaymentCompleted and tried to advance the order to PAID.
  3. Stop: it either overwrote the cancel or failed a state check and stopped.
  4. No refund: the saga's compensation logic only runs on a step failure, not on an external state change.

Causes ranked:

  1. Bypass: the cancel path wrote to the order and skipped the saga.
  2. No semantic lock: PENDING should have meant "in flight, cancel must go through the orchestrator".
  3. No version check on the order row.

The fix for this customer is a manual refund and an apology.

The design fix is that cancel becomes a signal to the saga, not a write to the order: the orchestrator receives "cancel requested", records it, and at its next transition decides — if before the charge, stop and cancel; if after, run the refund compensation; if after the pivot, reject the cancel and start a return flow instead.

Prevention is one rule: while a saga is in flight, every change to its aggregate goes through the saga.

Picture it The orders, saga and payments rows for order 123 second by second, so the missing refund is visible (see the orchestration pattern).

The setup: two writers touch order 123 with no coordination: the cancel handler and the checkout saga.

The trace: the three tables at each moment, with the order at version 3.

table state over timeruns offline
# illustrative output
T+0.0s  orders: 123 PENDING v3 | saga: CHARGING (cmd 7) | payments: (none)
T+0.5s  charge command 7 sent to payment
T+2.0s  cancel: UPDATE orders SET status='CANCELLED', version=4 WHERE id=123 AND version=3   -> 1 row ✓
        orders: 123 CANCELLED v4 | saga: CHARGING | payments: (none)
T+2.4s  payment: pay_77 CAPTURED 49.90
T+3.0s  saga gets PaymentCompleted: UPDATE orders SET status='PAID', version=4 WHERE id=123 AND version=3 -> 0 rows ✗
        saga logs "conflict", stops   (❌ TRAP: stopping is not compensating)
FINAL   orders: 123 CANCELLED v4 | payments: pay_77 CAPTURED | refunds: (none)

What you see: the support query that exposes the inconsistency.

reconciliation resultruns offline
# illustrative output
order_id | order_status | charge_status | refund
123      | CANCELLED    | CAPTURED      | (none)    <- customer paid, order cancelled

Why: compensation is triggered by a failure reply, and a rejected update is not a failure reply, so no one owed the refund noticed.

The fix: cancel becomes a signal recorded on the saga row, and the saga decides at its next transition.

cancel as a signalruns offline
UPDATE saga SET cancel_requested = true, version = version + 1
 WHERE order_id = 123 AND version = 7;     -- ✅ FIX: the saga row is the only writer of the order

What you see now: the same race, with the same final-state layout.

table state after the fixruns offline
# illustrative output
T+2.0s  saga: CHARGING, cancel_requested=true     orders: 123 PENDING
T+3.0s  PaymentCompleted -> saga sees cancel_requested -> issues refund (compensation)
T+3.4s  payments: pay_77 REFUNDED 49.90
FINAL   orders: 123 CANCELLED | payments: pay_77 REFUNDED | ✓ customer made whole

Land it Concurrent operations on a saga's aggregate must be routed through the saga, because only it knows which compensations are now owed.

Likely follow-ups
"You made cancel a signal to the saga. The cancel arrives while the charge command is in flight. What exactly does the orchestrator do?"

It records the signal and does not act yet, because the charge's outcome is unknown. Concretely: the cancel handler updates the saga row to set cancel_requested = true with the version check and returns "cancellation pending" to the customer.

The orchestrator's next transition is driven by the charge reply.

If the reply is PaymentFailed, the saga sees cancel_requested, skips any further steps, and moves to CANCELLED with the stock released.

If the reply is PaymentCompleted, the saga sees cancel_requested. The charge is compensable and the pivot has not passed, so it immediately issues the refund compensation and releases stock, ending in CANCELLED with the customer refunded.

If the charge times out, the normal timeout procedure (query payment) runs first, and only when the outcome is known does the cancel take effect. The customer's screen shows "cancelling" until the terminal state, which is honest.

decision tableruns offline
reply to charge     cancel_requested  saga does
PaymentFailed       true              release stock -> CANCELLED
PaymentCompleted    true              refund + release stock -> CANCELLED ✓ no money lost
(timeout)           true              query payment first, then one of the two rows above
PaymentCompleted    false             continue to RESERVE_STOCK
"How did the money get lost, mechanically — walk me through the two writes."

Two writers, no coordination. At T+2 seconds the cancel handler reads the order (status PENDING, version 3), writes status CANCELLED, version 4, and commits.

At T+3 seconds the payment reply arrives. The orchestrator read the saga's state before the cancel, and it now tries to advance the order to PAID. There are two possibilities.

If it does an unconditional update, the order becomes PAID, the cancellation is overwritten, the customer sees an active order they cancelled, and the money is at least accounted for.

If it does a version-checked update, the update affects zero rows, the orchestrator logs a conflict and stops — but stopping is not compensating, so the charge stands with no order and no refund.

The scenario describes the second: the saga's compensation logic runs only on a step's failure reply, and "my update was rejected" is not a failure reply.

The fix is that any rejected transition re-reads the aggregate and re-decides, and a CANCELLED order with a completed charge always means "refund".

"How do you find every other order that went through the same sequence?"

With a query that describes the inconsistency rather than the incident. Join the orders in CANCELLED against the payment service's charges, via the reconciliation job's bulk endpoints or a warehouse. Select those with a completed charge and no refund.

reconciliation queryruns offline
SELECT o.id, p.id AS payment_id, p.amount
  FROM orders o JOIN payments p ON p.order_id = o.id
 WHERE o.status = 'CANCELLED'
   AND p.status = 'CAPTURED'
   AND NOT EXISTS (SELECT 1 FROM refunds r WHERE r.payment_id = p.id);  -- Result: every owed refund

That is the affected set regardless of how each one got there. Then, for the root cause, the saga's history table shows which of those had a cancel timestamp between the charge command and its reply.

I would run the query for the full retention window, because this race has probably been happening at a low rate for as long as the cancel button has existed, and the customers who did not complain are still owed refunds.

Each one is refunded through the standard idempotent refund path, with a note on the order, and the total goes into the incident report as the cost of the bug.

"After the pivot, the customer wants to cancel. What does 'reject and start a return flow' mean for the customer?"

It means the response to the cancel is honest about where the order is.

If the shipment has been accepted by the carrier, "cancel" cannot stop the goods, so the API returns a state that says so — "this order has shipped; you can return it" — and offers the return process, which is its own workflow: a return authorisation, a label, a refund on receipt.

The customer-facing wording matters more than the mechanism; a silent failure or a generic error is the complaint.

Between the pivot and carrier acceptance there may be a window where the warehouse can still pull the parcel, and if the business wants to offer that, the saga exposes it as a "cancel-if-possible" signal whose reply is either "cancelled, refunding" or "too late, shipped", decided by the warehouse.

Either way, the saga stays in control of the order's state, and the return flow starts from a terminal state rather than fighting the saga.

Drill · Saga edges, outbox and change data capture

This group tests the unglamorous machinery that makes events reliable: what a timeout means for a saga step, the dual-write bug, and the outbox in production sizes.

Q61. "A saga step times out. Why is 'treat it as failed and compensate' wrong, and what should the orchestrator do instead?"

Reveal answer

Strong answer A timeout means the orchestrator does not know whether the step happened.

Suppose it compensates on the assumption of failure, and the step actually succeeded: the charge went through and the reply was lost.

The saga then refunds a payment it also never records. Worse, it releases stock that is then sold again while the customer's charge stands.

The orchestrator's job on a timeout is to resolve the unknown before acting. The best mechanism is a status query: every participant exposes "what is the state of command X?" keyed by the command's idempotency id, and the orchestrator asks.

The participant's answer decides the next move:

  • Done: the saga advances.
  • Never seen: the saga re-issues the command with the same id, which is safe because the participant is idempotent.
  • Unreachable: the saga waits and asks again on a schedule, up to an attempt limit, and then escalates.

The second mechanism is to make every command idempotent and simply re-send, relying on the participant to answer "already done" — which is fine for retryable steps but still leaves the orchestrator briefly ignorant for compensable ones.

What I would not do is choose a short timeout to "fail fast" on a compensable step; a saga step's timeout should be generous, because acting on a wrong guess costs more than waiting.

Picture it The same timed-out charge handled two ways: compensate on a guess, or ask first (see timeouts and the idempotent consumer).

The setup: the orchestrator sends charge command 42 for order 123 and waits 10 seconds for the reply.

Make the invisible visible: what each system really holds when the timeout fires.

table state at the timeoutruns offline
# illustrative output
t=0.0 s  orchestrator: saga 9a1 CHARGE_CARD, last_command_id=42 sent
t=0.8 s  payment:      processed_messages 42 | payments pay_77 CAPTURED 49.90 | reply published
t=0.9 s  reply lost on the way back
t=10  s  orchestrator: no reply -> TIMEOUT
         orchestrator believes: "charge unknown"
         payment holds:         "charge CAPTURED"      <- the orchestrator cannot see this

The trace: the wrong guess against the right question.

two reactions to the timeoutruns offline
❌ TRAP: treat timeout as failure
  t=10 s  saga: compensate -> release stock for order 123, state CANCELLED
  final   saga CANCELLED | stock released (resold later) | payments pay_77 CAPTURED | refunds (none)   ✗

✅ FIX: resolve the unknown
  t=10 s  saga: GET /commands/42 -> DONE {paymentId: pay_77}
  t=10 s  saga: advance to RESERVE_STOCK                                                             ✓

What you see: the participant answers from its idempotency table.

status queryruns offline
# illustrative output
GET /commands/42  ->  200 {"commandId":42,"state":"DONE","result":{"paymentId":"pay_77"}}
GET /commands/43  ->  200 {"commandId":43,"state":"UNKNOWN"}      # never received: safe to re-send with id 43

Why: a timeout only says the reply did not arrive, so only the participant can say whether the work happened.

Land it A timed-out saga step is a question, and the orchestrator has to ask it before it is allowed to reverse anything.

Likely follow-ups
"What does the participant's status endpoint look like, and what does it return for a command it is still processing?"

It is keyed by the command's idempotency id, not by the business entity, because the question is "what happened to command 42", and one order may have several commands.

GET /commands/42 returns one of four states: UNKNOWN — never received; IN_PROGRESS — received, not finished; DONE with the result payload, the same one the reply would carry; or FAILED with the reason.

The participant can answer this because its idempotency table already records each command's status in the same transaction as the work, so the endpoint is a read of that table.

four answersruns offline
{"commandId":42,"state":"UNKNOWN"}
{"commandId":42,"state":"IN_PROGRESS"}
{"commandId":42,"state":"DONE","result":{"paymentId":"pay_77"}}
{"commandId":42,"state":"FAILED","reason":"CARD_DECLINED"}

For IN_PROGRESS, the orchestrator waits and asks again, with backoff; it does not re-send, because the participant is already working. For UNKNOWN, it re-sends with the same id.

The endpoint costs nothing to build once idempotency exists, and it is the single most useful thing a participant can offer an orchestrator.

"The status endpoint says UNKNOWN, you re-send, and then the original command arrives late. What happens?"

The participant receives two commands with the same idempotency id, in either order.

Whichever arrives first inserts the id and does the work. The second hits the primary key, reads the stored outcome, and replies with it.

message timelineruns offline
# illustrative output
10:00:00  orchestrator sends cmd 42 (broker offset 700, delayed in the broker)
10:01:00  deadline passes; status says UNKNOWN; orchestrator re-sends cmd 42 (offset 731)
10:01:01  payment consumes offset 731: insert 42 ✓, charge pay_77, reply
10:01:40  payment consumes offset 700 (the original, late): insert 42 hits primary key -> replies stored result
10:01:41  orchestrator gets two replies for 42: first advances, second dropped as stale ✓

So the orchestrator receives two replies for command 42, and its own duplicate handling — matching on last_command_id and the version check — makes the second one a no-op.

The scenario where the original was delayed in the broker for longer than the deadline is exactly why the command id must be stable across re-sends: if the sweeper had minted a new id 43, the participant would have executed both.

The one remaining edge is the original arriving while the re-sent copy is mid-way through processing; the participant's insert then blocks or fails on the in-progress row, and the design from the idempotency question — block on the same transaction, or return 409 and let the caller retry — handles it.

"How generous is generous — what if the participant is down for an hour?"

Then the saga waits an hour, and the customer's order shows "processing" for an hour, and that is the correct behaviour for a compensable step whose outcome is unknown.

The deadline is not a promise to the customer; it is the interval at which the orchestrator checks.

Take a step deadline of 60 seconds and a sweeper that re-checks with backoff for up to ten attempts over an hour.

Then the saga stays correct through an hour of outage and goes to NEEDS_ATTENTION, which asks a human.

What must be generous is the tolerance before compensating, not the check interval.

The business promise — the customer sees a result within five minutes — is enforced separately: an alert on saga age in the waiting state, and a customer-facing status that says "payment is taking longer than usual".

Compensating at minute two because the promise was five minutes would produce refunds for charges that succeed at minute three.

"Does this reasoning apply to a retryable step after the pivot?"

The unknown is the same, but the response is simpler, because after the pivot there is no compensation to be wrong about.

A timed-out shipment-creation command is re-sent with the same command id after the deadline, and the participant's idempotency guard makes a duplicate harmless; there is no need to query first, because the worst case of re-sending is a no-op reply.

So post-pivot steps can use re-send-on-timeout, and the status query is an optimisation to avoid needless traffic.

The exception is a post-pivot step whose participant is not idempotent — a third-party call with no key — and that case needs the claim-then-query pattern from the exactly-once design.

The rule I use: before the pivot, timeouts are resolved by asking; after the pivot, by re-sending, provided the participant is idempotent, and if it is not, by asking anyway.

Q62 · Design. "A choreographed checkout across order, payment, and inventory works, but support cannot answer 'where is order 123?'. Design the status view without converting the saga to orchestration."

Reveal answer

Strong answer Requirements: a single place to see each order's progress, with timing, without changing how the three services coordinate.

Design: the saga is already emitting events — OrderCreated, PaymentCompleted or PaymentFailed, StockReserved or StockFailed, OrderCancelled — so a small saga-log service consumes all of them and maintains a table order_progress(order_id, last_event, last_event_at, events_json, expected_next, overdue_at).

Each event appends to the history and updates the expected next event and a deadline derived from a per-step time budget.

A sweeper marks orders whose deadline has passed as overdue and emits a metric per expected-next-event. That metric is the alert support was missing.

A query endpoint and a screen show the timeline for one order and a list of overdue ones.

The consumer is idempotent by event id, and it tolerates out-of-order arrival by storing events and computing state from the set rather than from the last one.

The trade-offs are two:

  • Lag: the view is eventually consistent with the saga by the event lag.
  • Observe only: it cannot re-issue a command, because in choreography there is no one to send it to.

That last limitation is the honest signal: if support then needs "retry this step", the saga has outgrown choreography, and this log becomes the state table of the orchestrator I would build next.

Picture it The order_progress row for order 123 after each delivered event, including one that arrives out of order and one duplicate (see the choreography pattern).

The setup: the saga-log service consumes the three services' topics and stores every event it sees, keyed by event id.

Make the invisible visible: the events as the log sees them, with their offsets.

deliveries to saga-logruns offline
# illustrative output
delivery  topic            partition:offset  event_id  event
1         inventory.events 1:55              e-2       StockReserved     order 123  10:02:15.1
2         orders.events    0:101             e-1       OrderCreated      order 123  10:02:14.0   <- arrives AFTER e-2
3         orders.events    0:101             e-1       OrderCreated      (redelivered duplicate)

The trace: the stored row after each delivery.

order_progress after each deliveryruns offline
after 1: events=[e-2 StockReserved]                      derived=UNKNOWN (no OrderCreated yet)   ✓ stored anyway
after 2: events=[e-1 OrderCreated, e-2 StockReserved]    derived=PENDING, expected_next=PaymentCompleted, overdue_at=10:03:16
after 3: duplicate e-1 -> primary key (order_id, event_id) hit, row unchanged                      ✓ de-duplicated
later:   events=[..., e-3 PaymentCompleted]               derived=CONFIRMED

What you see: support's answer to "where is order 123?" when the payment service goes quiet.

support screenruns offline
# illustrative output
order 123  PENDING   last_event=StockReserved at 10:02:15   expected_next=PaymentCompleted   OVERDUE since 10:03:16
timeline:  10:02:14 OrderCreated -> 10:02:15 StockReserved -> (nothing from payment)

Why: the log stores facts and derives the state from the set of facts, so arrival order and duplicates cannot corrupt it.

Land it A passive event log gives choreography its missing status view cheaply, and the day it needs a "retry" button is the day orchestration has earned its cost.

Likely follow-ups
"Support now wants a 'retry payment' button. What is the minimal change that stays choreographed?"

The button can exist without an orchestrator if it is a request to the owning participant rather than a command from a coordinator.

The saga-log service knows the order is waiting for a payment outcome. The button calls the payment service's own "reprocess order 123" endpoint.

That endpoint re-runs the payment handler for the original OrderCreated event, idempotently, and emits PaymentCompleted or PaymentFailed as usual. The rest of the choreography continues from there.

retry without an orchestratorruns offline
# illustrative output
support clicks "retry payment" on order 123
saga-log -> POST payment-service/orders/123/reprocess
payment  : handler re-run for OrderCreated e-1 (idempotent by event id) -> charge ✓
payment  : emits PaymentCompleted e-3
saga-log : appends e-3 -> derived=CONFIRMED

Each participant exposes one such endpoint, keyed by the event it consumed. That keeps every service owning its own behaviour and gives support a per-step retry.

What it does not give is a coordinated decision — "if payment cannot be retried, release stock" — because nobody holds the whole flow.

When support's second request is that kind of decision, the log's state table is the orchestrator's state table in waiting, and I make the switch then.

"How does the log compute state from a set of events that may arrive out of order?"

By treating the events as facts and deriving the state with a pure function over the set, rather than by applying each event as a transition. The row stores the events seen for the order as a list.

A function reads the list, with these rules in order:

  1. Cancellation: a cancellation event overrides everything.
  2. Failure: if StockFailed or PaymentFailed is present, the state is FAILED regardless of what else is there.
  3. Confirmed: if both PaymentCompleted and StockReserved are present, the state is CONFIRMED.
  4. Pending: if OrderCreated is present, the state is PENDING with the missing events as expected-next.
derive state from a setruns offline
static State derive(Set<String> types) {
    if (types.contains("OrderCancelled"))                         return State.CANCELLED;
    if (types.contains("PaymentFailed") || types.contains("StockFailed")) return State.FAILED;
    if (types.contains("PaymentCompleted") && types.contains("StockReserved")) return State.CONFIRMED;
    if (types.contains("OrderCreated"))                           return State.PENDING;
    return State.UNKNOWN;   // ✅ order of arrival does not matter: it is a function of the set
}

The function is re-run on every insert, so the order of arrival does not matter and a late OrderCreated slots in correctly. Duplicate events are de-duplicated by event id before the function runs.

The expected-next and deadline are derived from the same function, using the timestamp of the latest event present. This is small, testable with a table of event sets, and immune to the reordering that partition changes or retries cause.

"What would you cut under time pressure — what is the one-day version?"

The one-day version is the consumer and the table, with a SQL query as the interface. One consumer subscribed to the existing topics, appending each event to order_progress keyed by order id and event id, and a view that computes the state with the function above.

Support gets a read-only SQL screen or a two-line internal endpoint that returns the timeline for an order id. No sweeper, no overdue detection, no dashboard yet — the on-call engineer runs a query for orders in PENDING older than an hour when asked.

The next day adds the overdue sweeper and the metric, because that is what turns it from a lookup tool into an alert.

What I would not cut is idempotency by event id and storing the raw events, because the derived state can always be recomputed from the events but not the other way round.

"How does this differ from just querying each service's API for the order?"

Querying each service tells you its current view — the order is PENDING, payment has a charge, inventory has a reservation — but not the timeline, and not what did not happen.

The log has the timestamps of each step and can say "stock was reserved at 10:02:15, payment has not answered since 10:02:16", which is the answer support needs, and it can list every order in that condition, which a per-order query cannot.

It also works when a participant is down, which is usually when support is asking.

The per-service query is still useful as the second step — the log says payment is silent, and the payment service's status endpoint says why — so the status screen links to it.

And composing the per-service queries on every support request puts read load on three services' hot paths, whereas the log is a separate small table.

Q63. "Explain the dual-write problem with a concrete crash sequence, and why wrapping both writes in @Transactional does not help."

Reveal answer

Strong answer The dual-write problem is what happens when one operation must write to two systems that do not share a transaction — here, a database row and a Kafka message.

There are two crash sequences:

  • Commit, then crash: the order service inserts the order, commits, then the process is killed before send() runs. The order exists, no event was published, payment never charges, and the order sits in PENDING forever.
  • Send, then fail: the service sends the event first, then the insert fails on a constraint. Payment charges a card for an order that does not exist.

Wrapping both in Spring's @Transactional changes nothing, because the annotation manages the database transaction only; kafkaTemplate.send() inside it writes to the broker immediately, and if the commit then fails, the message is already out.

Delaying the send until after commit with a TransactionSynchronization reverses the risk: now a crash between commit and send loses the event.

No ordering of the two writes is safe, because the failure can always land between them.

The only fix is to write to one system and let something reliable copy to the other: the transactional outbox, where the event is a row in the same commit as the order, relayed to Kafka afterwards by a poller or by change data capture.

Spring Modulith's event publication registry is the in-process version of the same idea.

Picture it The orders table and the Kafka topic side by side at each step of both crash sequences, then the outbox version (see the outbox pattern).

The setup: the annotation covers the database write only; the Kafka send happens immediately.

OrderService.javaruns offline
@Transactional
public void placeOrder(Order o) {
    orderRepo.save(o);                                   // database write: commits when the method returns
    kafkaTemplate.send("orders.events", o.id(), event);  // ❌ TRAP: goes to the broker NOW, not at commit
}

The trace: what each system holds after every step.

sequence one: commit then crashruns offline
step                             orders table        topic orders.events
1 INSERT order 123 (open tx)     123 (uncommitted)   (empty)
2 COMMIT                         123 PENDING         (empty)
3 process killed before send     123 PENDING         (empty)       ✗ payment never hears; PENDING forever
sequence two: send then failruns offline
step                             orders table        topic orders.events
1 send OrderCreated 123          (nothing)           offset 812: OrderCreated 123
2 INSERT fails on constraint     (nothing)           offset 812 stays                  ✗ payment charges a phantom order

Why: the database and the broker have no shared commit, so the failure can always land between the two writes.

The fix: write the event as a row in the same commit and let a relay copy it to Kafka later.

outbox in the same commitruns offline
BEGIN;
INSERT INTO orders (id, status) VALUES (123, 'PENDING');
INSERT INTO outbox (id, aggregate_id, event_type, payload) VALUES ('e-1', '123', 'OrderCreated', '{...}');
COMMIT;      -- ✅ FIX: both rows or neither; the relay publishes e-1 afterwards, even after a restart

What you see now: the same crash after the commit, with the same columns.

crash after commit, with the outboxruns offline
step                             orders      outbox               topic orders.events
2 COMMIT                         123 PENDING e-1 (unpublished)   (empty)
3 process killed                 123 PENDING e-1 (unpublished)   (empty)
4 restart, relay publishes       123 PENDING e-1 published       offset 813: OrderCreated 123   ✓ delayed, not lost

Land it Two systems, one crash point between them, no shared commit — the only answer is to make the second write a consequence of the first, never a sibling.

Likely follow-ups
"What about Kafka transactions plus a database transaction — can you commit both together?"

No. A Kafka transaction covers Kafka partitions and consumer offsets; a database transaction covers the database.

There is no coordinator that spans them, so there is always an order — commit one, then the other — and a crash between the two leaves one committed and one not.

Spring's ChainedKafkaTransactionManager tried to make this convenient by committing them in sequence, and it was deprecated precisely because it gives "best effort one-phase commit", not atomicity: the window is small but real.

What Kafka transactions do give is atomicity between reading from one topic and writing to another, which is why they work inside Kafka Streams.

For the database-and-Kafka case, the outbox is the answer because it removes the second write from the request path entirely and makes Kafka a downstream consumer of the database's committed state.

"How would you prove to a sceptical team that the gap is real, not theoretical?"

With a test that induces it and a query that measures it.

The test is one of two:

  • Kill loop: save an order and send the event a thousand times while a second thread kills the process at random moments.
  • Injected fault (simpler): a Spring aspect throws after send() and before commit; then count orders in the database against messages on the topic.

The count will differ.

In production, run a reconciliation query that counts OrderCreated events per hour on the topic against orders inserted per hour, over the last month. It shows a small, steady deficit, and the deficit correlates with deploys and pod restarts.

reconciliation by hourruns offline
# illustrative output
hour   orders_inserted  OrderCreated_on_topic  gap
09:00  61,204           61,190                 14
10:00  60,877           60,877                  0
11:00  62,310           62,291                 19    <- deploy at 11:20
12:00  59,980           59,975                  5

That second number is what convinces a team, because it is their own orders and their own customers, and it is usually larger than they expect — a fraction of a per cent, which at scale is dozens of orders a day.

"Where does the TransactionSynchronization approach actually go wrong — is the window really that big?"

The window is small per request and large in aggregate.

With afterCommit, the send happens on the same thread after the database commit. The gap is the few milliseconds between the commit returning and the producer's buffer being flushed to the broker with an acknowledgement.

the afterCommit windowruns offline
# illustrative timeline
t=0 ms    database COMMIT returns             orders: 123 PENDING
t=1 ms    afterCommit: producer.send()        record sits in the producer buffer
t=4 ms    (SIGTERM / OOM kill)                ❌ TRAP: buffer discarded, no event on the topic
t=12 ms   broker would have acknowledged      (never happens)

The ways to land in it: a pod being terminated in a deploy, an out-of-memory kill, a broker being unreachable at that moment so the send fails, or the producer's own buffer being full so the send blocks and the request thread is interrupted.

Each is rare, but a service that restarts forty times a day and handles a thousand orders a minute hits the window a few times a day, and each hit is an order that never gets paid.

afterCommit also swallows exceptions by design, so the failed send is not even logged unless you add that. It is better than send-before-commit, and it is still a leak.

Q64. "Describe the transactional outbox mechanically, and state precisely what delivery guarantee it provides and why."

Reveal answer

Strong answer The service writes its business change and a row describing the event into an outbox table in the same local database transaction. Because it is one database, the commit is atomic: either both rows exist or neither does.

A separate relay then copies the rows to the broker:

  1. Read: select the unpublished outbox rows.
  2. Send: publish each with the aggregate id as the message key, so events for one entity stay ordered.
  3. Wait: hold for the broker's acknowledgement.
  4. Mark: set the row published.

With change data capture, a connector instead reads the database's transaction log and emits each committed outbox insert as a message, with no polling.

The guarantee is at-least-once delivery: the event can never be lost, because it was committed with the data, but it can be delivered more than once, because the relay may crash after sending and before marking, and on restart it sends again.

That is why the outbox always comes paired with idempotent consumers keyed on the event id stored in the row. Ordering is preserved per aggregate as long as the relay publishes rows for one aggregate in commit order to one partition.

Two version notes as of 2026: Debezium 3.x provides an outbox event router that maps the row's columns to topic, key, and headers; and Spring Modulith's event publication log gives the same guarantee within one application.

Picture it The orders, outbox, topic and consumer tables through one successful publish and one relay crash that produces a duplicate (see the outbox pattern and the idempotent consumer).

Make the invisible visible: what the single commit leaves behind.

table state after the commitruns offline
# illustrative output
orders:  id=123 | status=PENDING
outbox:  id=e-1 | aggregate_id=123 | event_type=OrderCreated | sequence=88 | published_at=NULL
topic orders.events: (empty)

The trace: the relay crashes after the broker acknowledged but before the row is marked.

relay with a crashruns offline
1 relay SELECT unpublished            -> e-1 (published_at NULL)
2 relay send(key=123, id=e-1)         -> broker offset 40 acknowledged   ✓
3 relay killed before UPDATE          -> outbox e-1 still published_at=NULL   ✗
4 relay restarts, SELECT unpublished  -> e-1 again
5 relay send(key=123, id=e-1)         -> broker offset 41 (same event id, new offset)

What you see: the consumer receives both copies and acts once.

consumer processed_messagesruns offline
# illustrative output
offset 40  event e-1  insert processed_messages(e-1) ✓  -> reserve stock for order 123
offset 41  event e-1  insert hits primary key             -> ✓ skipped, offset committed

Why: the mark-published write lives in the database and the send lives in Kafka, so a crash between them can only repeat the send, never drop it.

Land it The outbox turns "write to two systems" into "write to one and let a log carry it", and the price is at-least-once, which the consumer's guard table pays.

Likely follow-ups
"What columns does the outbox row have, and why each one?"

The minimum that lets the relay publish correctly without reading anything else.

one outbox rowruns offline
# illustrative output
id             e-1                       (UUID from the writer: the event id consumers de-duplicate on)
aggregate_type Order                     (chooses the topic)
aggregate_id   123                       (message key: one entity, one partition)
event_type     OrderCreated              (goes in a header)
payload        {"orderId":123,...}
created_at     2026-08-03 10:02:14
sequence       88                        (identity column, for the relay's ordering)
published_at   NULL

First, the id: a UUID generated by the writer, which becomes the event id consumers de-duplicate on.

aggregate_type and aggregate_id, which choose the topic and the message key so events for one entity share a partition. event_type, which goes in a header so consumers can route without parsing. payload as JSON or serialised Avro, the event body.

created_at, for ordering diagnostics and for the age metric. A sequence from an identity column, for the relay's ordering. And either published_at, null until the relay marks it, or no such column if rows are deleted after publishing.

Some teams add a headers map for the trace id so the consumer's span joins the producer's trace, which I recommend. Nothing about the destination lives anywhere but in this row, so the relay is generic.

"How does the relay preserve ordering when it runs as several instances with SKIP LOCKED?"

It does not, on its own, and this is the subtle part.

Two relay instances each lock a batch: instance A takes rows 1 to 50 and instance B takes 51 to 100.

reordering by two relaysruns offline
# illustrative output
relay A batch rows 1-50    (event 40: OrderCreated X ... slow, still sending)
relay B batch rows 51-100  (event 60: OrderPaid X)      publishes first
topic offset 900: OrderPaid X (event 60)      ✗ before
topic offset 901: OrderCreated X (event 40)

If B publishes first, event 60 for order X arrives before event 40 for the same order. There are three fixes.

Run one relay instance per outbox, using a leader lease — a row lock on a singleton row, or a Kubernetes lease — so there is exactly one publisher; this is the simplest and is enough for most volumes.

Or partition the outbox by aggregate id across instances, so all rows for one aggregate are always taken by the same instance, which needs a stable hash and is more code. Or accept out-of-order publishing and make consumers order-tolerant by version.

I default to the single leader with fast failover, and I keep SKIP LOCKED because it makes the failover safe when two instances briefly overlap.

"Is the outbox at-least-once even when the relay uses an idempotent producer?"

Yes. The idempotent producer de-duplicates retries within one producer session — the same batch re-sent after a lost acknowledgement.

The outbox's duplicate is different: the relay sent the message, the broker acknowledged it, and the relay crashed before updating the row; on restart, the relay reads the row again and calls send() again, which from the producer's point of view is a new message with a new sequence number, so the broker accepts it.

Even a transactional producer does not help, because the "mark published" write is in the database, not in Kafka. The only way to get exactly-once here would be to commit the mark and the send atomically, which is the dual-write problem again in the other direction.

So the consumer's guard on the event id is not optional, and the outbox row's id being the event id is what makes that guard work.

"How do you monitor that the outbox is healthy?"

Three numbers. The count of unpublished rows, which should hover near zero and grows when the relay is stuck or the broker is unavailable — alert above a few hundred for more than a minute.

The age of the oldest unpublished row, which is the delivery latency the consumers experience and the number the business cares about — alert above, say, 30 seconds.

And the relay's publish rate against the insert rate, which shows a relay that is alive but falling behind.

With CDC, the equivalents are the connector's status and its lag in milliseconds, plus the replication slot's retained WAL. I also add a synthetic check: a heartbeat row written every minute whose event a monitoring consumer expects to see within a minute, which proves the whole path end to end and catches the case where the metrics themselves are stale because the relay pod is gone.

Q65 · Scenario. "About 0.3% of orders never reach the payment service. The producer code is @Transactional and calls kafkaTemplate.send() after saving the order. Kafka reports no errors. Where are the events going?"

Reveal answer

Strong answer The symptom — a small, steady loss rate with no broker errors — is the signature of the dual-write gap rather than a Kafka fault.

Evidence: for a lost order, check whether the row exists in the orders table (it will), whether the broker ever received a message with that key (it will not), and correlate loss timestamps with deploys, pod restarts, and database errors.

Causes ranked:

  1. Unflushed buffer: send() is asynchronous by default and the application does not wait on the returned future. A pod that shuts down during a deploy discards messages still in the producer's buffer, and with forty deploys a day that alone reaches a fraction of a per cent.
  2. Rollback after send: a transaction that rolls back after a successful send loses the order rather than the event, so check that direction too.
  3. Weak acks: a producer configured with acks=0 or acks=1 loses messages on a broker leader change.

The fix is structural: move the event into an outbox row in the same transaction as the order and let a relay publish it, at which point a pod restart can only delay an event, never lose it.

As a stopgap, awaiting the send future and setting acks=all narrows the gap but does not close it.

Prevention: a reconciliation job that counts orders per hour against OrderCreated events per hour and alerts on drift, because that check would have found this in a day instead of a quarter.

Picture it Where one lost order lives: present in the orders table, absent from the topic, with the producer buffer as the hiding place (see the outbox pattern).

The setup: the producer code from the question; nobody waits on the future that send() returns.

OrderService.javaruns offline
@Transactional
public void place(Order o) {
    orderRepo.save(o);
    kafkaTemplate.send("orders.events", o.id(), new OrderCreated(o));  // ❌ TRAP: returns a future nobody awaits
}                                                                      // the record may still be in the buffer

Make the invisible visible: the producer buffer on one pod at the moment the deploy stops it.

producer buffer on pod-7runs offline
# illustrative output
10:20:00.000  order 901 saved, send() appended to batch  | buffer: [901]
10:20:00.040  order 902 saved, send() appended           | buffer: [901, 902]   (linger.ms not yet elapsed)
10:20:00.050  SIGTERM, grace period ends, process killed | buffer: [901, 902]   ✗ never flushed

What you see: the order rows exist and the topic has nothing for them.

orders versus topicruns offline
# illustrative output
orders table:   901 PENDING, 902 PENDING            (both rows committed)
topic orders.events, key 901: (no record)  key 902: (no record)
broker logs:    no errors                            <- nothing failed from Kafka's point of view
pod restarts:   pod-7 terminated 10:20:00.050        <- losses cluster just before each pod stops

Why: the database commit and the buffered send are two separate writes, and a pod stop can land between them.

What you see now: with the outbox, the same kill leaves a row that the relay still publishes.

table state with the outboxruns offline
# illustrative output
10:20:00.050  pod-7 killed
              orders: 901 PENDING, 902 PENDING | outbox: e-901, e-902 published_at=NULL
10:20:09.100  relay on another pod publishes e-901, e-902 -> topic offsets 5120, 5121   ✓ delayed, not lost

Land it A fraction of a per cent of lost events with no broker errors is the dual write showing itself, and the outbox is the only fix that removes the gap rather than shrinking it.

Likely follow-ups
"You added the outbox and the reconciliation still shows a deficit, smaller but not zero. What next?"

Then the loss has moved, and the reconciliation's two sides tell me where.

There are three cases, and the reconciliation tells them apart:

where the loss movedruns offline
orders  outbox row  topic record  payment saw it   => where it is lost
yes     yes         no            -                   relay (marks published before the ack, or acks=1)
yes     no          -             -                   a code path writes orders without the outbox
yes     yes         yes           no                  consumer (skipping error handler, offset reset)

In the first case the likely cause is a relay that marks a row published before the broker acknowledges: it sends asynchronously and updates on a callback that never fires on a crash. Another cause is a producer with acks=1 losing messages on a leader change.

The fix is to await the send's future and set acks=all with enable.idempotence=true.

In the second case, a code path creates orders without writing the outbox, such as an admin import or a second repository method, and the statement log finds it.

In the third case, the loss is on the consumer side: an error handler that skips records, or an offset reset. Each case has a different owner.

"Why does 0.3% correlate with deploys specifically — walk me through the producer buffer."

The Kafka producer does not send a message when send() is called; it appends it to an in-memory batch per partition and a background thread flushes batches when they fill or after linger.ms. send() returns a future that completes on acknowledgement.

If the application calls send() and returns the HTTP response without waiting on the future, the message may still be in the buffer when the pod receives SIGTERM.

Spring Kafka closes the producer cleanly on context shutdown if the termination grace period is long enough. Unless that happens, the buffer's contents are lost.

loss arithmeticruns offline
# illustrative numbers
12 pods stop per deploy x ~3 buffered records per pod = ~36 records lost per deploy
deploys every 20 minutes, each losing a handful of records, against thousands of orders in that time
loss rate: a fraction of a per cent (0.3%), clustered in the seconds before each pod's termination

The signature is that losses cluster in the seconds before each pod's termination, which the pod-restart timestamps confirm.

"What does the reconciliation query look like, concretely?"

Two counts per hour, joined. From the order database: SELECT date_trunc('hour', created_at), count(*) FROM orders GROUP BY 1 for the last 48 hours. From the topic: a small consumer, or the warehouse's copy of the events, giving count(*) FROM order_created_events GROUP BY hour.

A job diffs them and emits a metric for the gap per hour. For the current hour the gap is expected to be non-zero because of lag, so the alert applies to hours older than two.

A more precise version lists the order ids on the database side that have no event, using a left join in the warehouse. That produces the actual list to repair.

orders without an eventruns offline
SELECT o.id
  FROM orders o LEFT JOIN order_created_events e ON e.order_id = o.id
 WHERE e.order_id IS NULL AND o.created_at < now() - interval '2 hours';  -- Result: ids to re-emit

Those orders get their OrderCreated event re-emitted through the outbox by an administrative endpoint, and payment processes them.

The precise version is the one to build, because the count tells you there is a problem and the list lets you fix it.

Q66. "Polling relay versus Debezium change data capture for the outbox — trade-offs, and what FOR UPDATE SKIP LOCKED is doing in the poller."

Reveal answer

Strong answer A polling relay is a scheduled loop in the service that selects unpublished outbox rows, sends them, and marks them published.

It is simple, needs no extra infrastructure, and adds latency equal to the poll interval (typically 100 to 500 milliseconds) plus one query per interval on the database. It scales to a few thousand events a second before the polling itself becomes a load.

Change data capture with Debezium reads the database's write-ahead log — in PostgreSQL through a logical replication slot — and emits each committed insert as a Kafka message within milliseconds, with no polling load and no marking; outbox rows can be deleted right after insert.

It costs a Kafka Connect cluster to run, a replication slot to monitor (an unconsumed slot makes PostgreSQL retain WAL until the disk fills), and a schema of its own to learn.

FOR UPDATE SKIP LOCKED matters when the poller runs in several service instances.

Each instance locks the rows it selects, and other instances skip locked rows rather than waiting. So instances publish disjoint batches concurrently without double-sending.

Without it, two pollers either block each other or both publish the same rows.

The choice between the two relays:

  • Polling: for a service's first year and moderate volume.
  • CDC: when volume or latency demands it, or when the platform already runs Kafka Connect.

Picture it Two poller instances sharing one outbox with and without SKIP LOCKED, and the two relay topologies side by side (see the outbox pattern).

The setup: six unpublished outbox rows for orders 120 to 125, and two relay instances each asking for three.

poller queryruns offline
SELECT * FROM outbox
 WHERE published_at IS NULL
 ORDER BY sequence LIMIT 3
 FOR UPDATE SKIP LOCKED;

The trace: the lock state at each moment.

two pollersruns offline
# illustrative output
rows 1..6 unpublished
A: SELECT ... LIMIT 3 FOR UPDATE SKIP LOCKED  -> rows 1,2,3 (locked by A)
B: same query                                 -> skips 1-3, gets rows 4,5,6   ✓ disjoint batches, parallel
without SKIP LOCKED:
B: same query                                 -> waits on rows 1-3 until A commits   ✗ stalls
without FOR UPDATE at all:
B: same query                                 -> rows 1,2,3 again, both publish them ✗ double-send

Make the invisible visible: where each relay sits and what it costs.

topologiesruns offline
polling:  orders service -- INSERT order+outbox --> DB <-- SELECT every 200 ms -- relay (in service) --> Kafka
          latency = poll interval; load = one query per interval; nothing extra to run

CDC:      orders service -- INSERT order+outbox --> DB WAL --> replication slot --> Debezium (Kafka Connect) --> Kafka
          latency = milliseconds; load = none on tables; costs: Connect cluster + slot to monitor

What you see: the failure to watch for in each.

failure signalsruns offline
# illustrative output
polling stopped:   outbox unpublished count 12 -> 4,800, oldest age 40 s -> 15 min      (visible in the service's own database)
CDC stopped:       outbox empty, service healthy, but pg_replication_slots shows retained WAL growing   (service cannot see it)

Land it Start with the poller and SKIP LOCKED, and move to CDC when the polling load or the latency shows up on a graph.

Likely follow-ups
"What does the poller's query look like, exactly, and where does ordering come from?"

Something like SELECT * FROM outbox WHERE published_at IS NULL ORDER BY sequence LIMIT 100 FOR UPDATE SKIP LOCKED, inside a transaction; the relay publishes each row with the aggregate id as key, awaits the broker's acknowledgement, and then either updates published_at for the batch or deletes the rows, and commits.

Ordering within a batch comes from the identity column, which reflects insert order closely enough for one aggregate written by sequential transactions. The partial index ON outbox (sequence) WHERE published_at IS NULL makes the select cheap regardless of table size.

The catch is the gap from Chapter E8: an identity value is assigned at insert, but a transaction can commit after a later-numbered transaction.

So a poller that remembers "I have published up to sequence 500" can skip row 498 that commits late.

late-committing rowruns offline
# illustrative output
tx1 takes sequence 498, still open
tx2 takes sequence 499, 500, commits
poller: WHERE sequence > last_seen(497) -> sees 499, 500, publishes, last_seen=500
tx1 commits row 498                      ❌ TRAP: 498 < last_seen, never selected
✅ FIX: WHERE published_at IS NULL  -> 498 is selected on the next pass

Selecting by published_at IS NULL rather than by "greater than last sequence" avoids that, at the cost of the ordering not being strictly by sequence across batches.

"With Debezium, what does the outbox event router actually do, and what does the connector configuration look like?"

Debezium's default output is a change event describing the row — before, after, operation — on a topic named after the table.

The outbox event router is a single message transform that reshapes that into the business event: it takes the aggregate_type column to choose the topic, aggregate_id as the key, payload as the value, and can move other columns into headers; it also drops delete events so the immediate delete-after-insert trick does not produce a second message.

In the connector configuration that is transforms=outbox and the router class, with table.include.list set to the outbox table only, a route-by field of aggregate_type, and a topic naming pattern.

connector settingsruns offline
transforms=outbox
transforms.outbox.type=io.debezium.transforms.outbox.EventRouter
table.include.list=public.outbox
transforms.outbox.route.by.field=aggregate_type

The connector needs a PostgreSQL role with replication privilege and a publication for the table.

It is configuration, not code, and it runs on a Kafka Connect cluster the platform team operates.

"What is the failure mode of each, in an incident?"

The poller's failures are visible and local: if it stops, the unpublished count grows in the service's own database, the age metric climbs, and restarting the service restarts the poller; if the broker is down, the poller retries and the table absorbs the backlog.

Its bad day is the bloat scenario from the outbox-query question.

CDC's failures are outside the service: the Connect cluster is down, the connector task failed and needs a restart through the Connect REST API, or the replication slot is retaining WAL on a database the service team does not run; the service keeps writing happily while its events go nowhere, so the monitoring must be on the connector, not the service.

CDC also has a snapshot phase on first start or after slot loss, which can be hours on a large table. So the poller fails in ways the service team sees; CDC fails in ways the platform team must watch for them.

"How does SKIP LOCKED interact with a crash mid-batch?"

Cleanly, because the lock is transactional. The poller selects and locks 100 rows, publishes 60 of them to the broker with acknowledgements, and the pod dies.

Its transaction never committed, so the database releases the lock and the published_at updates for the 60 roll back. Every one of the 100 rows is still unpublished as far as the table is concerned.

The next poller instance selects them again and publishes all 100, so the 60 are sent twice, which the consumer's guard on the event id absorbs.

crash mid-batchruns offline
# illustrative output
poller A: locks rows 1-100; sends rows 1-60 (acked); pod dies      outbox: rows 1-100 published_at=NULL (rolled back)
poller B: locks rows 1-100; sends rows 1-100                       topic: rows 1-60 twice ✗ duplicates
consumer: processed_messages already holds e-1..e-60               ✓ 60 skipped, 40 processed

Without SKIP LOCKED, another instance running concurrently would have blocked on the locked rows until the crash released them — a stall of up to the database's dead-connection detection time, which can be minutes.

So SKIP LOCKED gives concurrency during normal operation and fast recovery after a crash, and the at-least-once duplicate is the price both times.

Q67 · Design. "Design the outbox for a payments service handling 2,000 payments a second. Cover the schema, ordering, the relay, cleanup, and monitoring."

Reveal answer

Strong answer Requirements: no payment event may be lost; events for one payment must arrive in order; latency under 100 milliseconds; the table must not grow forever. Schema: outbox(id uuid primary key, aggregate_type, aggregate_id, event_type, payload jsonb, created_at, sequence bigint generated always as identity).

The identity column gives a commit-independent ordering hint, but since transactions can commit out of sequence order, the relay orders by sequence and tolerates small gaps rather than assuming density.

Ordering on the wire: message key = aggregate id, so one payment's events share a partition; the topic gets 60 partitions for headroom.

Relay: at 2,000 events a second, polling is marginal, so I use Debezium 3.x with the outbox event router reading the logical replication slot. The connector runs with two tasks for availability.

Cleanup is free: the service deletes each outbox row in the same transaction that inserts it. Debezium still sees the insert in the log, so the table stays near empty.

Monitoring has four signals:

  • Lag: connector lag in milliseconds.
  • Slot: replication slot retained-WAL bytes, with an alert at a few gigabytes.
  • Age: the count of outbox rows older than one minute, which should be zero.
  • Reconciliation: payments per minute compared with events per minute.

Trade-off: a Kafka Connect cluster to operate. What I would not do is publish directly from the request thread or delete rows by a nightly job that competes with the write path.

Picture it One payment through the insert-and-delete outbox, with the numbers for partitions and WAL at 2,000 payments a second (see the outbox pattern).

The setup: the payment and its event are written in one transaction, and the outbox row is deleted in the same transaction.

PaymentService transactionruns offline
BEGIN;
INSERT INTO payments (id, order_id, status) VALUES ('pay_77', 123, 'CAPTURED');
INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload)
       VALUES ('e-9', 'payments', 'pay_77', 'PaymentCaptured', '{...}');
DELETE FROM outbox WHERE id = 'e-9';   -- ✅ FIX: table stays empty; the log still has the insert
COMMIT;

Make the invisible visible: what the table holds against what the log holds.

table versus logruns offline
# illustrative output
after COMMIT   outbox table: 0 rows
               WAL:          insert payments pay_77 | insert outbox e-9 | delete outbox e-9
Debezium       reads the insert of e-9 -> router -> topic payments, key pay_77, one message (delete dropped)

The trace: the sizing arithmetic.

sizingruns offline
# illustrative numbers
2,000 events/s / ~200 events/s per consumer thread (5 ms each) = 10 partitions as the floor
60 partitions = 6 x headroom; ordering key = payment id, so one payment stays on one partition
WAL: 2,000 tx/s x ~2 KB = ~4 MB/s  -> ~14 GB per hour of slot lag

What you see: the dashboard on a healthy day, and the number that wakes you.

monitoringruns offline
# illustrative output
connector lag             140 ms
outbox rows older than 1m 0
retained WAL for slot     0.3 GB    (alert at a few GB)
payments/min vs events/min 120,000 vs 120,000

Land it At this volume the log is the relay, the table is transient, and the replication slot's WAL size is the metric that will wake you if you forget it.

Likely follow-ups
"Debezium is down for two hours. What happens to the database, and what happens when it comes back?"

The database keeps working and keeps retaining WAL for the slot. The retained-WAL alert fires within minutes, so someone knows.

retained WAL over the outageruns offline
# illustrative numbers: 2,000 tx/s x ~2 KB = ~4 MB/s
Debezium stops          retained WAL   0 GB
+10 min                 retained WAL   ~2.4 GB    (alert fires)
+1 h                    retained WAL   ~14 GB
+2 h                    retained WAL   ~30 GB     (roughly; must stay under max_slot_wal_keep_size and disk)

Provided the disk has that headroom and max_slot_wal_keep_size is set above it, nothing else is affected.

When the connector returns, it resumes from the slot's confirmed position and streams two hours of outbox inserts in order at whatever rate the connector and the broker can take — typically tens of thousands of events a second — so the backlog clears in a few minutes, with consumers seeing a burst.

The rows were deleted at insert time, but the deletes do not matter because the inserts are in the log.

If the slot had been invalidated by the size cap, the connector would need a new slot and a snapshot, and the events written in the gap would have to be re-emitted from the payments table by a repair job.

"Why 60 partitions, and what does that mean for consumer scaling?"

The arithmetic: at 2,000 events a second with a p99 processing time of, say, 5 milliseconds, one consumer thread handles around 200 a second.

So ten partitions is the floor, and sixty gives six times headroom for growth and for slow consumers.

It also bounds the hot-key problem: one very active merchant's events go to one partition, and with sixty partitions that partition still carries a manageable share.

The consequence for consumers is that any group can scale to sixty instances and no further, and that a group with six instances gets ten partitions each, which is fine.

The cost is sixty sets of files and replication per broker, which is nothing at this size. The number is chosen once, because changing it breaks the ordering contract, so I would rather over-provision by a factor of five than revisit it.

"Under time pressure, what would you cut — could you start with the poller?"

Yes, and I would say so explicitly: a poller with SKIP LOCKED, a partial index, and immediate deletion after publish handles a few thousand events a second on a reasonable PostgreSQL instance, so it is viable at launch if Kafka Connect is not already running.

What I would keep from the design: the schema exactly as specified, so switching to CDC later is a connector configuration and not a migration; the key and partition choices, because they are the ordering contract; the age-of-oldest-unpublished metric; and the reconciliation.

What I would drop for now: the Connect cluster and the slot monitoring, since there is no slot.

The poller's known limits — its latency of a poll interval and the polling load on the database — would go on a dashboard with a threshold, and crossing it is the trigger for CDC. That is a day's work rather than a week's.

"How do you deal with a payment whose events must span two topics — payments and a ledger topic?"

The outbox handles it naturally, because each outbox row names its own aggregate type and therefore its own topic, and both rows are written in the same transaction as the payment.

So a capture writes a PaymentCaptured row routed to the payments topic and a LedgerEntryPosted row routed to the ledger topic, atomically.

two rows, one commitruns offline
# illustrative output
outbox: e-9  | aggregate_type=payments | event_type=PaymentCaptured    -> topic payments
outbox: e-10 | aggregate_type=ledger   | event_type=LedgerEntryPosted  -> topic ledger
both committed together ✓; the two topics may still be read in either order ✗

What the outbox cannot promise is ordering between the two topics — a consumer of both may see the ledger entry before the payment event — and cross-topic atomicity in the consumer's view, which is the point made about multi-topic aggregates earlier.

If a consumer needs both together, it should consume one topic and treat the other's data as carried in the event, or the two should be one event on one topic with the ledger consumer filtering.

I avoid designing a consumer that must join two topics in order.

Q68 · Scenario. "After a Kafka rebalance during a deploy, the inventory service reserved stock twice for about 200 orders, and the order service shows duplicate order rows for a dozen of them. Separate the two problems and fix both."

Reveal answer

The real test Whether you can tell redelivery from a real duplicate and know which guard each one needs.

Strong answer These are two different bugs.

The 200 double reservations are redelivery: during the rebalance, partitions moved from the old pods to the new ones, and messages the old pods had processed but not yet committed the offset for were read again by the new pods.

Evidence: the same event id appears twice in inventory's logs, on two different pods, seconds apart.

The cause is a consumer without an idempotency guard, and the fix is the guard table — insert the event id into processed_events in the same transaction as the stock update, so the second delivery hits the primary key and stops.

The dozen duplicate order rows are a different thing. The same order id cannot be inserted twice if the id is the primary key. So one of two things happened:

  • Two ids: the producer created two orders, most likely because the client retried a POST without an idempotency key during the deploy's brief unavailability.
  • No business key: the orders table has no uniqueness on the business key.

Evidence: compare the duplicate rows' ids and creation times with the gateway's request log. The fix there is an idempotency key on order creation, enforced by a unique constraint, plus returning the existing order on a repeat.

Prevention for both: idempotency at every boundary as a template requirement, and a deploy strategy that drains consumers before stopping pods (graceful shutdown with offset commit).

Picture it The inventory and orders tables for one affected order, showing why the two problems need two different guards (see the idempotent consumer).

The setup: reserving stock for order 123 is a consumer; creating order 123 is a POST. The rebalance hits both.

The trace: problem one, redelivery of event e-77 after the partition moved.

redelivery during the rebalanceruns offline
# illustrative output
pod-A  consumes offset 4812 (e-77, reserve 1 of SKU-X for order 123)  stock available 10 -> 9, reserved 1
pod-A  offset commit pending ... rebalance: partition moves to pod-B     ✗ offset 4812 never committed
pod-B  consumes offset 4812 (e-77 again)                                 stock available 9 -> 8, reserved 2   ✗ double reservation

What you see: problem two, the duplicate rows next to the gateway log.

duplicate order rowsruns offline
# illustrative output
orders:   id=8001 client=c-9 cart=cart-5 created=10:20:01.2
          id=8002 client=c-9 cart=cart-5 created=10:20:03.9      <- different ids, so a primary key cannot catch it
gateway:  POST /orders client=c-9 -> 503 (pod stopping)   10:20:01.5
          POST /orders client=c-9 -> 201                  10:20:03.9   (retry, no Idempotency-Key)

Why: the first is the same message twice and the second is two different requests for one intent, so a guard on the message id cannot fix the second.

The fix: a guard table for the consumer and a unique key for the producer, both committed with the work.

the two guardsruns offline
-- consumer: one transaction
INSERT INTO processed_events (event_id) VALUES ('e-77');          -- second delivery hits the primary key, stops
UPDATE stock SET reserved = reserved + 1 WHERE sku = 'SKU-X';

-- producer: orders table
ALTER TABLE orders ADD CONSTRAINT uq_client_key UNIQUE (client_id, idempotency_key);

What you see now: the same two incidents after the fix.

after both guardsruns offline
# illustrative output
pod-B  consumes offset 4812 (e-77): insert processed_events hits primary key -> ✓ skipped, stock stays reserved 1
POST /orders client=c-9 key=k-5 -> 503, then retry with key=k-5 -> 200 returns order 8001   ✓ one row

Land it Redelivery is fixed on the consumer with a guard table; duplicate creation is fixed on the producer with an idempotency key, and confusing the two means fixing only one.

Likely follow-ups
"You added the guard table and the double reservations stopped, but now some orders are never reserved at all. What next?"

The guard is swallowing a real failure.

The likely bug: the guard insert committed on its own, before the business update. That can mean a separate, earlier transaction, or a business update that throws after the guard commit.

Either way the event is marked processed while the reservation never happened, and the redelivery hits the guard and is dropped.

guard committed aloneruns offline
# illustrative output
tx1: INSERT processed_events e-78 ... COMMIT         ❌ TRAP: guard commits alone
tx2: UPDATE stock ... throws (deadlock)              reservation never happens
redelivery of e-78: insert hits primary key          ✗ dropped; order 130 never reserved
✅ FIX: one transaction for guard + update, so the failure rolls back both

The fix is to put the guard insert and the reservation in one transaction, so a failure rolls back both.

A second variant: the primary-key violation is being caught too broadly, and a different constraint failure — a stock-row conflict — is being treated as "already processed". The catch must be specific to the guard table's constraint.

I would confirm with the reconciliation between orders and reservations, and repair the missing ones by re-emitting the events. The lesson is that idempotency guards are only correct when they commit with the work, and a guard that commits alone converts at-least-once into at-most-once.

"How exactly does graceful shutdown of a Kafka consumer work in Spring, and what setting is usually wrong?"

On SIGTERM, Spring's context shutdown asks the listener containers to stop; each container finishes the current poll's records, commits their offsets, and calls consumer.close(), which sends a leave-group request so the rebalance happens immediately rather than after the session timeout.

The setting that is usually wrong is Kubernetes' terminationGracePeriodSeconds, which defaults to 30 seconds.

grace period arithmeticruns offline
batch in progress: 500 records x 100 ms = 50 s needed
terminationGracePeriodSeconds: 30 s   -> killed at 30 s  ✗
~200 records processed, offsets uncommitted -> redelivered to the new owner
✅ FIX: grace period > worst-case batch (e.g. 60 s) or max.poll.records smaller

The fixes are a grace period longer than the worst-case batch, a smaller max.poll.records, and Spring Boot's spring.lifecycle.timeout-per-shutdown-phase set to match.

The second common mistake is the readiness probe still passing during shutdown, so with HTTP consumers the pod receives new requests while stopping; the container's shutdown hook should flip readiness first.

"For the duplicate orders, what does the idempotency key on order creation look like end to end?"

The client — the web front end or the mobile app — generates a UUID when the user opens the checkout page, keeps it in the page state, and sends it as Idempotency-Key on the POST; a retry after a timeout or a network error sends the same key.

The gateway passes it through.

The order service has a unique constraint on (client_id, idempotency_key) and inserts the order and the key in one transaction.

A second POST with the same key hits the constraint. The service returns the existing order with 200 and the same body, rather than 201 and a new one.

HTTP exchangeruns offline
# illustrative output
POST /orders   Idempotency-Key: k-5   -> 201 Created  {"orderId":8001}
POST /orders   Idempotency-Key: k-5   -> 200 OK       {"orderId":8001}   ✓ same order, no second row

The key expires after a day. The gateway's request log is where I verify the incident's cause: the duplicate orders' requests will show the same client, seconds apart, with no key or with different keys.

Without client cooperation, a weaker server-side guard is a uniqueness rule on cart id, which catches most double-submits.

"Why did the rebalance happen during the deploy at all, and can it be avoided?"

Because each pod stopping and starting is a membership change in the consumer group, and in the classic protocol every change triggers a full rebalance. A rolling deploy of ten pods is up to twenty membership changes.

It can be reduced to near zero with the three mechanisms from the rebalance question: static membership with a stable group.instance.id per pod so a restarted pod reclaims its partitions without a rebalance if it returns within the session timeout; the cooperative-sticky assignor or the KIP-848 protocol so any rebalance that does happen moves only the necessary partitions; and clean shutdown so offsets are committed before partitions move.

Even with all three, the design has to assume rebalances will happen — a pod crash is one — so the idempotent consumer stays mandatory; the deploy tuning just makes the redelivery rare rather than routine.

Q69. "Walk through the idempotent consumer precisely: what is stored, in which transaction, and what happens on each crash point."

Reveal answer

Strong answer The consumer keeps a table processed_events(event_id primary key, consumer, processed_at) in its own database. On each message it does four things in order:

  1. Begin: open one database transaction.
  2. Guard: insert the event id.
  3. Work: perform the business change, then commit.
  4. Offset: let Kafka commit the offset.

Each crash point lands somewhere safe:

  • Before the database commit: nothing was written and the offset was not committed. Kafka redelivers and the second run does the work cleanly.
  • After the database commit, before the offset commit: the work is done. Kafka redelivers, the insert hits the primary key, the consumer returns without doing anything, and the offset is committed this time.
  • After both: normal.

A duplicate from a producer's re-send is handled the same way, because the event id is the producer's outbox row id, not something the consumer generates.

Two details make it hold:

  • Catch the violation: the primary key violation must be treated as "already done", not as an error that triggers a retry loop.
  • Offset after commit: the offset is committed only after the database commit. In Spring Kafka the default acknowledgement mode commits after the listener returns, and a rolled-back transaction throws, so the order is right by default.

The table grows one row per event, so it is pruned by age — a week is plenty, since redelivery happens within minutes.

Picture it The guard table, the stock row and the committed offset at each crash point for one event, e-1 at offset 100 (see the idempotent consumer and the outbox).

The setup: the listener does the guard insert first, inside one transaction.

ReserveStockListener.javaruns offline
@KafkaListener(topics = "inventory.commands")
@Transactional
public void on(ReserveStock cmd) {
    try {
        processed.insert(cmd.eventId());          // 1st statement: duplicate fails fast
    } catch (DataIntegrityViolationException e) { // ✅ narrow this to the guard table's constraint
        return;                                   // already done
    }
    stock.reserve(cmd.sku(), cmd.qty());          // business change, same transaction
}

The trace: what exists after a crash at each point.

crash pointsruns offline
# illustrative output
crash point                      processed_events  stock reserved  committed offset  next delivery
before COMMIT                    (empty)           0               99                ✓ does the work
after COMMIT, before offset      e-1               1               99                ✓ guard hit, skipped, offset 100 committed
after offset commit              e-1               1               100               ✓ nothing to redeliver

What you see: the log of the middle case.

consoleruns offline
# illustrative output
10:02:01.100 offset=100 event=e-1  guard insert ok, stock reserved=1, COMMIT
10:02:01.101 (pod killed before the offset commit)
10:02:09.400 offset=100 event=e-1  guard insert hits primary key -> skipped, offset 100 committed

Why: the guard row and the business change commit together, so after any crash the database either has both or neither.

Going deeper Two precisions on the Spring Kafka side, as of Aug 2026.

First, the acknowledgement mode. The default AckMode is BATCH, which commits the offsets for a whole poll's records after the listener has returned for all of them.

That is still "after the work". But a crash mid-batch redelivers every record in the batch, not only the one in progress, so the guard table sees more duplicates than with RECORD mode. RECORD mode commits after each record, at the cost of more commit calls.

BATCH versus RECORDruns offline
# illustrative output: poll returns offsets 100-104, crash while processing 103
BATCH : committed offset still 99  -> redelivers 100-104, guard hits on 100, 101, 102 (3 duplicates skipped)
RECORD: committed offset 102       -> redelivers 103-104, guard hits: 0

With a database transaction per record and a container configured with a KafkaTransactionManager or a chained approach, the ordering is the same: database commit, then offset.

Second, the guard insert. It should be the first statement in the transaction, so a duplicate fails fast before any business work.

The exception to catch is the specific unique violation: in Spring, DataIntegrityViolationException narrowed by constraint name. Never catch a generic exception, or a real failure will be silently treated as "already done".

Land it The guard row and the business change share one commit, and the offset commits after both, so every crash point lands on a state that the next delivery handles correctly.

Likely follow-ups
"What if the consumer's side effect is not in the database — an HTTP call to another service?"

Then the single-transaction trick does not cover it, and the choice is between making the remote call idempotent and using the claim pattern.

If the remote service accepts an idempotency key, the consumer passes the event id as the key. The guard table still records the event locally after the call succeeds.

A redelivery either finds the guard row, or, if the crash was between the call and the guard insert, re-calls with the same key and the remote service returns the stored result.

crash between call and guardruns offline
# illustrative output
1st delivery: POST /notify  Idempotency-Key: e-1 -> 200 (sent)    guard insert not yet done, pod dies
redelivery:   POST /notify  Idempotency-Key: e-1 -> 200 (stored result, no second send)  ✓ then guard insert

That is exactly-once effect through the remote service's guard.

If the remote call has no key, the consumer uses the claim-then-confirm pattern from the exactly-once design: insert a claim row keyed by event id, commit, call, then update to confirmed, with a sweeper that queries the remote side for stuck claims.

Either way the local guard row is not enough on its own once the side effect leaves the database.

"Why is the event id the producer's outbox row id and not something derived from the payload?"

Because the guarantee needs an id that is the same across every delivery of the same event and different for every distinct event, and the outbox row's UUID has exactly that property: it was generated once, in the producer's transaction, and every copy the relay sends carries it.

A hash of the payload would collide for two genuinely different events with identical content — two "reserve 1 unit of SKU X for order 123" events after a legitimate re-order — and would differ for the same event if a header or a timestamp changed on re-send.

A consumer-generated id would be different on each delivery, which is useless. The partition-and-offset pair identifies a delivery, not an event, and changes after a repartition or a re-drive from the dead-letter topic.

So the producer-assigned id in the message, typically in a header, is the only stable identity, and it is the outbox's id column.

"How big does the guard table get and how do you prune it safely?"

One row per event consumed, which is why pruning matters.

guard table sizeruns offline
1,000 events/s x 86,400 s = 86.4 million rows a day
kept 7 days             = ~605 million rows
daily partitions: DROP the oldest partition = instant, no bloat

Redelivery happens within minutes of the original — a rebalance, a crash, a relay restart — and a re-drive from a dead-letter topic within days, so keeping seven days is safe, and I keep it as a configurable window.

The prune is a batched delete by processed_at older than the window, in chunks, or better, a partitioned table by day where dropping the oldest partition is instant and creates no bloat.

The index that matters is the primary key on the event id, which is what the guard insert hits.

A row that has been pruned and then redelivered — a re-drive after a month — would be processed twice, and the defence for that rare case is the business-level version check, which is why I keep both.

"How do you test the crash points rather than just reasoning about them?"

With a test that runs the consumer against a real database in a container and a real or embedded broker, and injects a failure at each point.

A Spring aspect or a test double on the repository throws after the guard insert but before the business update, and the test asserts that the transaction rolled back, the offset was not committed, and a second delivery completes the work once.

A second test kills the offset commit: a listener that throws after the database transaction commits. It asserts that the redelivery hits the guard and the work count is still one.

A third test sends the same event twice deliberately.

duplicate delivery testruns offline
@Test void sameEventTwiceReservesOnce() {
    listener.on(new ReserveStock("e-1", "SKU-X", 1));
    listener.on(new ReserveStock("e-1", "SKU-X", 1));          // duplicate delivery
    assertEquals(1, stockRepo.reserved("SKU-X"));              // ✅ one reservation
}

These are integration tests that take seconds each, and they run in CI. In production, the count of guard-table hits per hour is the observable: a baseline of a few per rebalance is normal, a spike means redelivery is happening for a reason worth looking at, and zero forever probably means the guard is not wired in.

Q70 · Scenario. "The outbox poller's batch query has gone from 3 milliseconds to 2 seconds. The outbox table has 180 million rows, all but a few hundred already published. What happened and what do you do?"

Reveal answer

Strong answer The symptom — the same query, now slow, on a table that has grown — says the query is scanning published rows to find the unpublished ones.

Evidence: EXPLAIN ANALYZE on the poller's query; if it shows a sequential scan or an index scan over created_at that then filters out millions of published rows, the index does not match the predicate.

Causes ranked:

  1. No partial index: there is no index on WHERE published_at IS NULL, so the index covers all 180 million rows and the filter runs afterwards.
  2. Bloat: in PostgreSQL, millions of dead row versions from the published-at updates that vacuum has not reclaimed, so even a good index visits dead tuples.
  3. No pruning: the table was never pruned because nobody wrote the cleanup job.

Fix in order:

  1. Index: create the partial index concurrently, so the query touches only the few hundred unpublished rows.
  2. Delete: remove published rows older than a few days, in chunks of ten thousand with a pause, so it does not hold locks or flood the WAL.
  3. Vacuum: run VACUUM to reclaim space.

Prevention: delete published rows continuously in the relay's own loop, or move to change data capture where rows are deleted at insert time.

The lesson from Chapter E8 applies unchanged: the outbox is just a table, and its queries need the same index and bloat discipline as any other.

Picture it The outbox table of 180 million rows with 180 waiting to be sent, and how many rows the poller's query touches with and without the partial index (see the outbox pattern).

The setup: the poller's query, unchanged since the table was small.

poller queryruns offline
SELECT * FROM outbox
 WHERE published_at IS NULL
 ORDER BY sequence LIMIT 100
 FOR UPDATE SKIP LOCKED;

Make the invisible visible: where the wanted rows sit among the unwanted ones.

table stateruns offline
# illustrative output
outbox: 180,000,000 rows
  published_at NOT NULL : 179,999,820 rows  (sequence 1 .. 179,999,820)
  published_at NULL     :         180 rows  (sequence 179,999,821 .. 180,000,000)
index on (sequence) walks from sequence 1 and discards published rows until it finds 100 wanted ones

What you see: the plan before the fix.

EXPLAIN ANALYZEruns offline
# illustrative output
Limit
  -> Index Scan using outbox_sequence_idx on outbox
       Filter: (published_at IS NULL)
       Rows Removed by Filter: 179,999,820      <- the work is all here
Execution Time: 2104 ms

Why: the index orders every row by sequence, and the filter that keeps only unpublished rows runs after the index has already visited the published ones.

The fix: an index that contains only the wanted rows.

partial indexruns offline
CREATE INDEX CONCURRENTLY outbox_unpublished_idx
    ON outbox (sequence) WHERE published_at IS NULL;   -- ✅ FIX: index holds 180 rows, not 180 million

What you see now: the same plan layout after the fix.

EXPLAIN ANALYZEruns offline
# illustrative output
Limit
  -> Index Scan using outbox_unpublished_idx on outbox
       Rows Removed by Filter: 0
Execution Time: 3 ms

Land it The outbox query must touch only unpublished rows, and a partial index plus continuous pruning keeps it that way regardless of how many events the service has ever sent.

Likely follow-ups
"You added the partial index and it is still 800 milliseconds. What next?"

Then the index is not being used, or it is being used and the time is elsewhere. EXPLAIN (ANALYZE, BUFFERS) answers which.

There are three outcomes, and the plan output tells me which to do first:

plan to actionruns offline
plan shows                                  root cause                               action
Seq Scan, index not used                    predicate differs from the index        make the query say published_at IS NULL; run ANALYZE
Index Scan, huge buffer count               index bloated with dead entries         REINDEX CONCURRENTLY; check autovacuum
time spent in FOR UPDATE lock waits         another poller or long transaction      look in pg_locks

For the first, an example mismatch is a query that says published = false while the index says published_at IS NULL. The planner's statistics can also be stale after the large delete, so I run ANALYZE.

For the second, I check pg_stat_user_tables for the dead-tuple count and the last autovacuum time, to confirm vacuum has been keeping up.

"Why does bloat happen on this table specifically, and what setting prevents it?"

Because the poller updates every row once — setting published_at — and in PostgreSQL an update writes a new row version and leaves the old one as a dead tuple until vacuum reclaims it.

A table that receives a million inserts and a million updates a day accumulates a million dead tuples a day, and autovacuum with default settings triggers only when dead tuples exceed 20% of the table plus a threshold, which on a 180-million-row table is 36 million dead rows before it runs.

The settings are per-table, so vacuum can run after ten thousand dead rows instead of 36 million:

per-table autovacuumruns offline
ALTER TABLE outbox SET (autovacuum_vacuum_scale_factor = 0.01,
                        autovacuum_vacuum_threshold = 10000);   -- ✅ FIX: default waits for ~20% of the table

The better structural fix is to delete rows after publishing instead of updating them, and to let vacuum reclaim the deletes, or to delete at insert time with CDC so the table never holds published rows at all.

"How do you delete 180 million rows without taking the service down?"

In batches, with a pause, and never in one statement. A single DELETE ... WHERE published_at < now() - interval '3 days' would run for an hour, hold locks, generate tens of gigabytes of WAL, and saturate replication.

Instead a loop: delete one chunk, commit, sleep 100 milliseconds, and repeat until zero rows are affected.

one chunk of the loopruns offline
DELETE FROM outbox
 WHERE id IN (SELECT id FROM outbox
               WHERE published_at < now() - interval '3 days'
               LIMIT 10000);          -- ✅ FIX: milliseconds per batch, then COMMIT and sleep 100 ms

Each batch is milliseconds, replication keeps up, and the poller's own query is not blocked because it selects different rows.

When it is done, the table's file is still 180 million rows of mostly free space; plain VACUUM makes the space reusable but does not shrink the file, and pg_repack or VACUUM FULL in a maintenance window rebuilds it — VACUUM FULL takes an exclusive lock, so pg_repack is the online choice.

For the future, partitioning by day and dropping partitions replaces the whole exercise.

"What would the alert have been that caught this a month ago?"

Two would have worked. The poller's query latency, exported by the service as a timer, with an alert at ten times its baseline — the growth from 3 milliseconds was gradual and would have crossed 30 milliseconds weeks before it reached 2 seconds.

And the table's size or row count, from pg_stat_user_tables or a nightly count, with an alert at a sensible ceiling for a table that is supposed to be near-empty — a million rows would have been a clear anomaly.

A third, more general one is the dead-tuple ratio per table from the same statistics view, which catches bloat on any table, not only the outbox.

The lesson I would put in the postmortem is that any table with a "should be small" invariant needs an alert on its size, because the query that depends on it being small degrades slowly and then all at once.

Q71. "With Debezium reading PostgreSQL, what is a replication slot, and how does an unattended one take down the database?"

Reveal answer

Strong answer A replication slot is PostgreSQL's way of promising a consumer that it will keep every write-ahead log segment from the consumer's last confirmed position onward, so the consumer can disconnect and resume without missing changes.

Debezium creates a logical slot and advances it as it publishes. The promise is the hazard: if the connector stops — crashed, misconfigured, or simply deleted without dropping the slot — PostgreSQL keeps retaining WAL for it indefinitely.

WAL accumulates at the database's write rate, the disk fills, and PostgreSQL stops accepting writes; the whole service goes down because a monitoring tool was left switched off.

The defences:

  • Monitor: watch pg_replication_slots for the retained bytes per slot and alert well before the disk is at risk.
  • Cap: set max_slot_wal_keep_size (available since PostgreSQL 13) so a lagging slot is invalidated rather than allowed to fill the disk. The connector must then resnapshot.
  • Runbook: make dropping the slot part of the connector's decommissioning runbook.
  • Heartbeat: run the connector with the task restarts and heartbeat table that Debezium recommends, because a heartbeat keeps the slot advancing even on a quiet database.

The same failure exists with any log-based replication, including physical standbys with slots.

Picture it A slot nobody reads: the slot row, the retained WAL and the disk at four moments after the connector is deleted (see the outbox pattern).

The setup: the connector was deleted from Kafka Connect, but nobody dropped the slot it created.

Make the invisible visible: the slot looks like this in PostgreSQL.

pg_replication_slotsruns offline
# illustrative output
slot_name | active | restart_lsn | retained
debezium  | f      | 0/5A000000  | 41 GB        <- nobody is reading; PostgreSQL still keeps every segment after restart_lsn

The trace: the disk over time at a write rate that adds about 10 GB of WAL an hour.

disk over timeruns offline
# illustrative numbers
Monday 18:00   connector deleted, slot left behind   WAL retained   0 GB   disk 40%
Monday 22:00   +4 h                                  WAL retained  40 GB   disk 65%
Tuesday 02:00  +8 h                                  WAL retained  80 GB   disk 90%   <- alert should have fired
Tuesday 04:00  +10 h                                 disk 100%  ✗ PostgreSQL stops accepting writes, the whole service is down

Why: a slot is a promise to keep the log until the consumer reads it, and a deleted connector never reads again.

The fix: cap what a slot may retain, and drop the slot when its consumer is gone.

postgresql.conf and cleanupruns offline
# postgresql.conf
max_slot_wal_keep_size = 50GB        # ✅ FIX: a lagging slot is invalidated instead of filling the disk

-- when the connector is retired
SELECT pg_drop_replication_slot('debezium');

What you see now: the same view when the cap is hit.

pg_replication_slotsruns offline
# illustrative output
slot_name | active | wal_status | retained
debezium  | f      | lost       | (WAL freed)      <- slot invalidated, disk safe; the connector must resnapshot

Land it A replication slot is a promise to keep the log forever until someone reads it, and the alert on retained WAL is what keeps that promise from becoming an outage.

Likely follow-ups
"The disk is at 95% and climbing because of a slot. What do you do in the next ten minutes?"

First I confirm it is the slot. This query shows each slot and how much WAL it is holding:

confirm the slotruns offline
SELECT slot_name, active,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
  FROM pg_replication_slots;
-- Result (illustrative): debezium | f | 41 GB   -> an inactive slot with tens of GB is the cause

Then I decide between reviving the consumer and dropping the slot.

If the Debezium connector can be restarted within minutes — a failed task, a paused connector — I restart it and watch the retained size fall as it streams; that preserves the events.

If the connector is gone or cannot catch up before the disk fills, I drop the slot with SELECT pg_drop_replication_slot('debezium'), which frees the WAL at the next checkpoint, and I accept that the connector will need a new slot and a snapshot, and that the events written since the slot stalled must be reconstructed from the source tables.

Dropping the slot is the emergency brake; the database must not stop accepting writes.

"What does the heartbeat table do, and why is it needed on a quiet database?"

Debezium advances the slot's confirmed position only when it processes and acknowledges a change from a table it captures.

Take a database where the captured tables are quiet but other tables are busy, or a shared instance where another database is busy.

The WAL grows from the other activity. The slot cannot advance because no captured change has arrived, so retained WAL grows even though the connector is healthy.

without and with a heartbeatruns offline
# illustrative output
no heartbeat:   outbox idle for 6 h, other tables busy   connector "RUNNING"   retained WAL 12 GB -> 70 GB   ✗
heartbeat 10 s: heartbeat row updated every 10 s         confirmed position advances   retained WAL ~0.1 GB   ✓

The heartbeat setting, heartbeat.interval.ms, makes the connector emit a periodic heartbeat event; combined with heartbeat.action.query, which runs a small UPDATE on a dedicated heartbeat table in the captured database, it guarantees a captured change every interval, so the slot advances continuously.

Without it, a connector on a quiet table looks fine on every metric while the retained WAL climbs. It is one of the settings I check first in any Debezium review.

"What does the connector do when it starts with a new slot — what is the snapshot and how long does it take?"

A new slot has no history, so the connector cannot replay past changes; it takes a snapshot instead, reading the current contents of every captured table in a consistent transaction and emitting each row as a read event, then switches to streaming from the slot's position, which was created at the snapshot's start so nothing is missed.

For an outbox table that is kept near-empty the snapshot is instant. For a large source table — hundreds of millions of rows — it can take hours and generate a corresponding burst on the topic, which consumers must be prepared for.

Debezium's incremental snapshot reads in chunks while streaming continues, which avoids the long pause.

The gap to remember is that events that would have been emitted between the old slot's death and the new snapshot are represented by the current state, not the history: an outbox row inserted and deleted in that gap is gone, which is why a repair job from the source tables follows a slot loss.

"How do you decommission a connector properly?"

In this order:

  1. Consumers: stop them depending on its topic, or move them to the replacement.
  2. Connector: delete it through the Connect REST API, which stops the tasks.
  3. Slot: drop the replication slot in PostgreSQL, separately and explicitly. Deleting the connector does not drop the slot; it leaves it inactive and retaining WAL.
  4. Publication: drop the publication the connector created.
  5. Alert: remove the retained-WAL alert for that slot, so nobody is paged for a slot that no longer exists.
runbook statementsruns offline
SELECT pg_drop_replication_slot('debezium');   -- the step that gets forgotten
DROP PUBLICATION IF EXISTS dbz_publication;    -- use the publication name your connector created

I write it as a runbook with the exact statements. The slot is the step that gets forgotten, and it is the one that takes the database down a week later, on a quiet night, when nobody remembers there was a connector.

The same runbook applies to any logical replication consumer, including a subscription for a database migration that is finished.

Q72 · Design. "A consumer's side effect is a call to a third-party shipping API that is not idempotent and has no idempotency key. Design for exactly-once effect anyway."

Reveal answer

Strong answer Requirements: never create two shipments for one order, even when the event is redelivered or the process crashes around the external call.

The guard-table pattern alone does not work, because the external call cannot be in my database transaction: a crash after the call but before the commit loses the guard row, and the redelivery calls again.

Design: split the operation into a local claim and a confirmed record.

  1. Claim: on the event, in one transaction, insert a row shipment_request(order_id primary key, state='CLAIMED', claimed_at). The primary key on order id means a redelivery finds the claim and does not proceed to a second call.
  2. Commit the claim.
  3. Call: make the external call to the carrier.
  4. Confirm: on success, update the row to CREATED with the carrier's shipment id and commit.

Recovery is the crucial part. A sweeper finds rows stuck in CLAIMED older than a minute.

Before calling again, it queries the carrier by a reference I control. Most APIs accept a client reference or let you search by order number. If a shipment already exists, record it; if not, call again.

That query-before-retry closes the gap the missing idempotency key leaves. Trade-offs: a tiny window where a shipment exists and my row says CLAIMED, resolved by the sweeper; and a dependency on the carrier's search.

What I would not do is retry the call blindly, and I would push the vendor for an idempotency key while running this.

Picture it The shipment_request row and the carrier's own records at each step, including a crash between the call and the confirmation (compare the outbox and the idempotent consumer).

The setup: the carrier call cannot join my transaction, so my table records intent before the call and outcome after it.

The trace: a crash in the narrow window, then recovery.

claim, call, crash, recoverruns offline
# illustrative output
step                                       shipment_request           carrier records
1 tx: INSERT claim, COMMIT                 123 CLAIMED                (none)
2 POST /shipments ref=order-123            123 CLAIMED                SH-9 (ref order-123)
3 pod killed before the confirm UPDATE     123 CLAIMED                SH-9
4 event redelivered: insert claim          primary key hit            ✓ no second call
5 sweeper (age > 1 min): GET ?ref=order-123 -> finds SH-9
6 UPDATE state='CREATED', carrier_id='SH-9' 123 CREATED SH-9          SH-9                ✓ exactly one shipment

What you see: the naive version for comparison, with the same columns.

naive: call then guardruns offline
# illustrative output
1 consume event, POST /shipments            (no guard row yet)         SH-9
2 pod killed before the guard commit        (no guard row)             SH-9
3 event redelivered: no guard row, POST     (no guard row)             SH-9, SH-10   ✗ two parcels for order 123

Why: the external call cannot be in my transaction, so only a claim committed before the call can survive a crash, and a query by reference settles the doubt.

Land it Claim locally, call once, confirm locally, and on doubt query before retrying — that sequence gives exactly-once effect against an API that offers no help.

Likely follow-ups
"The carrier has no search endpoint either. What is left?"

Then I cannot verify, so I minimise the window and accept a bounded manual case.

The claim row still prevents every duplicate except the one caused by a crash between the call and the confirmation write. The remaining risk is that narrow window.

claim statesruns offline
CLAIMED     -> (call ok, confirm write) -> CREATED
CLAIMED     -> (crash in the window, older than 1 min, no search endpoint) -> UNVERIFIED + ticket   ✓ no blind retry

I shrink it: the confirmation update is the very next statement after the call returns, with no work in between, and the process handles termination signals by finishing in-flight calls before exiting.

For the crash that still lands in the window, the sweeper cannot ask the carrier, so it does not retry automatically; it marks the claim as UNVERIFIED and raises a ticket, and a person checks the carrier's portal or waits for the carrier's daily manifest file, which most carriers provide and which can be reconciled automatically.

That converts a silent duplicate into a small manual queue. And I would make the missing idempotency key or search a contractual request to the vendor, with the incident count as the argument.

"What is the changed-requirement version — the carrier adds an idempotency key next quarter?"

Then the design simplifies but does not disappear. The claim row stays, because it is still what stops a redelivered event from making a second call on my side, and the sweeper stays for stuck claims.

What changes is the sweeper's action: instead of querying by reference before retrying, it can simply retry with the same key — derived from my order id — and the carrier returns the existing shipment.

The verification step becomes unnecessary and the UNVERIFIED manual queue goes away. The claim row's state field also gets simpler, because the "called but unconfirmed" state is no longer dangerous.

So the migration is to pass the key on every call from the day it is available, keep the query-before-retry for a release as belt and braces, and then remove it.

I would keep the claim table permanently; it costs one insert and it is what makes my side deterministic.

"Under time pressure, what is the minimum you would ship?"

The claim row with the primary key on order id and the sweeper that only alerts. That is: insert the claim, commit, call the carrier, update to CREATED, commit; and a scheduled job that lists claims older than a minute in CLAIMED state and pages someone.

It prevents every duplicate from redelivery, which is the common case, and turns the rare crash-in-the-window case into a human check rather than an automatic retry that might duplicate. The query-before-retry automation can follow once the carrier's search behaviour has been tested.

What I would refuse to ship is the naive version — consume the event, call the carrier, commit the guard — because it duplicates on every rebalance, and the naive fix for that, retrying on timeout, duplicates on every timeout.

Half a day for the claim table is cheap next to a week of duplicate parcels.

"How is this different from the transactional outbox — is it not the same pattern?"

It is the same shape applied to the other direction, and noticing that helps.

The outbox makes an outbound message a consequence of a committed local row. A relay retries until the message is acknowledged, and consumers de-duplicate.

The claim pattern makes an outbound side effect a consequence of a committed local row, with a sweeper that retries until the effect is confirmed.

The difference is what "acknowledged" means: a broker acknowledges idempotently thanks to the consumer's guard, whereas the carrier does not, so the sweeper has to verify before retrying instead of retrying freely.

If the carrier had an idempotency key, the claim pattern would be exactly an outbox whose relay calls HTTP instead of Kafka, and in fact a generic outbox with pluggable destinations is a reasonable way to implement it.

The insight is that every external side effect wants a local row that records intent before the effect and outcome after it.

Drill · Read models, CQRS and event sourcing

This group tests whether you can build and operate the derived views a service system runs on, and whether you know when event sourcing is a burden rather than a benefit.

Q73. "CQRS: what problem does it solve, what does it cost, and when is it a mistake?"

Reveal answer

Strong answer CQRS — command query responsibility segregation — means using a different model to write than to read.

The write model is normalised, guarded by rules, and owned by one service; a read model is a denormalised projection built by consuming events, shaped for one screen or one query, and stored wherever that query is cheapest: a flat table, Elasticsearch, Redis.

It solves the problem that the shape that makes writes safe (many small tables with constraints) is the shape that makes reads slow (many JOINs), and in a service system it also solves the lost-JOIN problem across boundaries.

The costs are four:

  • Components: another component per read model.
  • Consistency: eventual consistency between write and read.
  • Rebuild: a procedure for when the projection changes.
  • Read-your-writes: extra work at the interface.

It is a mistake when applied to an entire system by default: a simple CRUD screen served from the write model is faster to build, always consistent, and needs no rebuild story.

I introduce a read model when a specific query is measurably too slow or crosses a service boundary, and I keep everything else on the plain model.

Picture it The "orders with customer and product details" screen served by a five-table join, and then by one pre-joined row kept up to date from events (see the CQRS pattern).

The setup: the screen needs order 123, its items, the customer name and the product names, and the customer and product tables belong to other services.

the queryruns offline
SELECT o.id, c.name, p.title, i.qty, o.total
  FROM orders o JOIN order_items i ON i.order_id = o.id
  JOIN customers c ON c.id = o.customer_id      -- owned by the customer service
  JOIN products  p ON p.id = i.product_id        -- owned by the catalogue service
 WHERE o.customer_id = ? ORDER BY o.created_at DESC LIMIT 20;

Make the invisible visible: the same screen as one row per order in a read model.

read model tableruns offline
# illustrative output
write side:  orders(123, cust 7, total 49.90) | order_items(123: sku X x2) | (customers, products live in other services)
events:      OrderCreated 123 | CustomerRenamed 7 "Asha K" | ProductRenamed X "Desk lamp"
order_view:  order_id=123 | customer_name="Asha K" | items_text="Desk lamp x2" | total=49.90 | last_seq=812

What you see: the endpoint before and after, from the database's own numbers.

latency evidenceruns offline
# illustrative output
before: GET /my-orders   p99 900 ms   pg_stat_statements: top by total time, 5-table join + sort, indexes already used
        reads : writes = 100 : 1
after:  GET /my-orders   p99  12 ms   one indexed read on order_view(customer_id, created_at)

Why: the write model is shaped for safe updates, and the read model is shaped for one question, so neither compromises for the other.

Land it CQRS is a per-query decision, not an architecture, and the good version of it is one read model that exists because a graph showed it was needed.

Likely follow-ups
"Give me the concrete graph that would justify the first read model."

A query latency graph for one endpoint, with the database's own numbers behind it.

For example, the "orders with customer and product details" endpoint is at a p99 of 900 milliseconds.

pg_stat_statements shows its query at the top by total time. EXPLAIN shows a five-table join with a sort, already using the right indexes, so indexing is exhausted.

pg_stat_statementsruns offline
# illustrative output
rank  total_time   calls     mean_ms  query
1     41 min       182,000   13.5     SELECT o.id, c.name, p.title ... (5-table join)
2      6 min        90,000    4.0     SELECT ... FROM payments ...

Alongside it, the read-to-write ratio for the data: a hundred reads per order change, which says the cost of maintaining a denormalised copy on each change is paid back a hundred times.

And the cross-boundary signal: two of those five tables belong to other services, so the join is currently reaching into their databases or composing calls. Any two of those three justify the read model for that endpoint.

Without them, the right response to a slow query is an index or a rewrite, which is cheaper than a projection.

"Where should the read model's storage be — same database as the write model, or separate?"

It depends on what the read model is for.

If it exists to remove a cross-service join and the read load is moderate, a table in the consuming service's own database is fine and simplest — one database, one backup, one transaction for the projection's guard and update.

If it exists for load isolation — a hundred reads per write hammering the transactional database — it belongs on a separate store so the reads cannot slow the writes: a read replica for the simplest cases, a separate PostgreSQL instance for a flat table, Elasticsearch for search and faceting, Redis for a hot key-value view.

Each separate store adds an operational surface and its own rebuild procedure.

I start in the same database when the goal is shape, and move it out when the goal is load, because moving a projection between stores is cheap — it is rebuilt from events anyway.

"Is it CQRS if the same service serves both models?"

Yes; CQRS is about separating the models, not the deployables.

One service can do all four of these in one codebase and one database:

  1. Write to its normalised tables.
  2. Publish events from its outbox.
  3. Consume its own events to maintain a denormalised view table.
  4. Serve reads from that view.
one service, two modelsruns offline
POST /orders -> orders + order_items + outbox (one commit)
outbox -> relay -> orders.events -> same service's projection -> order_view
GET /my-orders -> order_view only          ✓ reads and writes no longer share a model

That is the lightest form and is often the right one: the write model keeps its constraints, the view is shaped for the screen, and the eventual consistency is a few milliseconds through the in-process path.

Where people confuse it is thinking CQRS requires a separate read service or an event store; it does not. It only requires that reads and writes stop sharing one model.

The separate read service is what you build when the read model spans several services' data or needs its own scaling, which is a deployment decision layered on top.

"What does the rebuild story cost, and can you avoid needing one?"

The rebuild is a consumer that starts from the beginning of the event history and writes into a fresh table, which needs the history to still exist — retention on the topics long enough, or an event archive — and a procedure to switch reads over when it catches up.

The cost is a few days to build the first time and the discipline to keep the history.

You can avoid it only by never changing the projection, which does not happen, or by making the read model rebuildable from the write model's current state instead of from events — a batch job that re-derives every row from the owning services' bulk endpoints.

That second option is often the pragmatic one for projections over data that is small enough to re-read in an hour, and it does not depend on event retention.

For large or history-dependent views the event replay is the only route, and that is when infinite retention or an archive becomes a requirement.

Q74 · Scenario. "Users place an order, the confirmation page shows it, they click 'My orders', and the new order is missing. It appears if they refresh five seconds later. Support has forty tickets. Fix it properly."

Reveal answer

Strong answer The symptom is a read-your-writes violation: the confirmation is served by the order service (the write model), and "My orders" is served by a read model that has not yet consumed the event.

Evidence: the read model's lag metric, which will show a few seconds, and traces of the two requests hitting different services. It is working as designed, and the design forgot the user. Fixes, from cheapest to most robust.

  1. Front-end pin: the front end adds the just-created order to the list from the create response and pins it there until the list contains it. It is invisible to the user, needs no backend change, and is enough for most products.
  2. Version token: after a write, the API returns a token (the event's sequence or timestamp). The list endpoint accepts it. If the read model has not reached that version, the endpoint either waits up to a short bound, or falls back to querying the order service for that user's most recent orders and merges.
  3. Less lag: use CDC instead of polling, and a consumer that is not starved.

The fix I would ship is the first plus the lag reduction. I would add the version token only if a mobile client or a third party needs it.

What I would not do is route all "My orders" reads to the write model; that removes the read model's reason to exist and puts the read load back on the transactional database.

Picture it The write side, the read model and the browser at each second after the order is placed, then the same sequence with a version token (see the CQRS pattern).

The setup: the confirmation page is served from the order service, and "My orders" from the read model that consumes the order events.

The trace: the rows on each side, with the event sequence number.

read-your-writes violationruns offline
# illustrative output
t=0.0 s  write side  orders: 123 PENDING, seq 812       read model order_view: last_applied_seq 811, no row 123
t=0.3 s  GET /orders/123 (order service)  -> 123 shown on the confirmation page            ✓
t=1.2 s  GET /my-orders  (read model)     -> list without 123                              ✗ user thinks the order is lost
t=5.0 s  projection applies seq 812        read model: row 123, last_applied_seq 812
t=6.0 s  user refreshes                    -> list with 123                                ✓

What you see: the customer's view of the same minute.

evidenceruns offline
# illustrative output
projection lag metric: 4.8 s (p95)
trace: POST /orders -> order-service (200, 412 ms); GET /my-orders -> order-view-service (200, 18 ms, 0 rows for order 123)
support: 40 tickets "my order disappeared, then came back"

The fix: the create response carries the sequence, and the list call hands it back.

version tokenruns offline
POST /orders            -> 201 {"orderId":123, "seq":812}
GET /my-orders?minSeq=812
   read model last_applied_seq=811 < 812 -> wait up to 500 ms, else merge order 123 from the order service
   ✅ FIX: the list the user sees always contains the order they just placed

What you see now: the same second-by-second view.

after the fixruns offline
# illustrative output
t=1.2 s  GET /my-orders?minSeq=812  read model at 811 -> merges 123 from the write side -> list contains 123   ✓
t=5.0 s  read model reaches 812; later calls need no merge

Land it Eventual consistency is fine for everyone except the person who just made the change, and the interface owes that one person their own write.

Likely follow-ups
"You shipped the front-end fix and the tickets keep coming from the mobile app. What next?"

Then the mobile app is a second client that did not get the fix, and the fix has to move to the API. I would implement the version token: the create-order response includes the event's sequence, the mobile app sends it on its next list call, and the read service waits briefly or merges from the write side if the read model is behind.

That takes the fix out of each client's hands. Meanwhile I check the mobile app's actual behaviour, because it may be fetching the list before the create response has even returned, in which case no consistency mechanism helps and it is a client bug.

And I look at the lag number again: if the read model is five seconds behind under normal load, that is a slow projection, not just a consistency gap, and reducing it to a few hundred milliseconds would shrink the ticket volume across every client regardless.

"How do you make the read endpoint 'wait for version X' without holding threads?"

The wait is a bounded poll on a cheap local value, not on the database.

The projection consumer keeps its latest applied sequence in memory and in a small table.

The read handler, given a required version, checks the in-memory value. If it is behind, it sleeps 50 milliseconds and checks again, up to a ceiling of, say, 500 milliseconds.

bounded waitruns offline
# illustrative output
GET /my-orders?minSeq=812   applied=811  sleep 50 ms
                            applied=811  sleep 50 ms
                            applied=812  ✓ serve from the read model after 100 ms
(if still 811 at 500 ms -> fetch order 123 from the order service and merge)

With virtual threads or a reactive stack the sleep does not hold a platform thread; with a servlet stack, a few hundred milliseconds per request that needs it is acceptable because only requests immediately after a write carry the header.

If the ceiling passes, the handler falls back to fetching the specific order from the write service and merging it.

The alternative — routing the read to the write side whenever a version header is present — is simpler and fine when the fraction of such reads is small; I measure the fraction before choosing.

"Why not just serve 'My orders' from the write model for a few seconds after a write?"

That is the fallback in the version-token design, and it is acceptable for the one user's recent orders because it is a small indexed query by customer id.

What I would not do is route the whole list to the write model, because the list is the read-heavy query the read model exists to protect the transactional database from, and because the list's shape — with product names and shipping status — needs joins across services that the write model cannot do.

So the compromise is narrow: fetch this user's orders created in the last minute from the write model, and merge them into the list from the read model, de-duplicating by order id.

merge by order idruns offline
read model: [122, 121, 120]          write side (last minute): [123, 122]
merged by id, newest first: [123, 122, 121, 120]     ✓ 122 appears once, though it is in both sources

That costs one small query on the write side per post-write read, and it preserves the read model's role for everything else. The merge logic is where bugs live, so it gets a test with an order present in both sources.

"How do you decide between the front-end fix and the API fix as the 'proper' one?"

By counting clients and by who owns the promise.

If there is one web client and the team owns it, the front-end fix is proper: it is the cheapest, it is invisible to the user, and it makes no backend promise that other clients might rely on.

If there are several clients, or third-party clients, or the API is documented as read-your-writes, the promise has to live in the API, because each client cannot be trusted to implement the workaround and a public API that is inconsistent for its own writes is a support burden forever.

The version token is the standard way to make that promise cheaply. The lag reduction is proper in both cases because it shrinks the window for everyone, including the cases neither fix covers — a user on two devices.

I would state the decision in the ticket with the client count, so the next engineer knows why.

Q75. "What does event sourcing cost that people discover only after adopting it?"

Reveal answer

Strong answer Event sourcing stores each aggregate as its full history of events and rebuilds current state by replaying them. The surprises come in four areas.

  • Performance: an account with a hundred thousand events cannot be replayed on every request. You need snapshots (periodic saved states), and then snapshot versioning and invalidation.
  • Schema evolution: every event ever written must remain readable forever. A renamed field means an upcaster that translates old events on read, and those upcasters accumulate for the life of the system.
  • Reads and queries: the event store answers "what happened to aggregate X" and nothing else. Every list, search, or report needs a projection, so CQRS is mandatory rather than optional.
  • Deletion: privacy law requires erasing a person's data, and an immutable log cannot erase. You end up encrypting personal fields per user and destroying the key, which is a system of its own.

Add the cultural cost that few engineers have done it before and debugging means reading event streams.

It pays off in domains where the history is the product — ledgers, audit-critical workflows, anything where "how did we get here" is a business question — and it is a burden everywhere else.

Picture it One account's event stream, and the four bills it sends later: replay time, a renamed field, a query it cannot answer, and an erasure request (see the event sourcing pattern and CQRS).

The setup: the event store is an append-only table, one stream per account.

events tableruns offline
# illustrative output
stream   seq     type            schema  payload
acct-9   1       AccountOpened   v1      {"name": enc(k-9, "Asha Kumar"), "currency": "EUR"}
acct-9   2       Deposited       v1      {"amount": 100.00}
...
acct-9   99,800  Deposited       v1      {"amount": 12.50}
acct-9   100,000 Withdrawn       v2      {"amount": 40.00}

Make the invisible visible: the replay cost, with and without a snapshot.

replay arithmeticruns offline
# illustrative numbers
no snapshot : 100,000 events x 0.02 ms = 2,000 ms to load acct-9 on every request   ✗
snapshot @ seq 99,800 (state saved) : read 1 snapshot + replay 200 events x 0.02 ms = ~4 ms   ✓

What you see: a field renamed in the code, and the upcaster that keeps old events readable.

upcasterruns offline
# illustrative output
stored v1 event : {"amount": 100.00, "ccy": "EUR"}
code now expects: {"amount": 100.00, "currency": "EUR"}
upcaster v1->v2 : copies "ccy" to "currency" while reading; the stored row never changes   ✓ (and the upcaster stays forever)

The trace: an erasure request handled by destroying the key.

crypto-shreddingruns offline
before : key store holds k-9 | acct-9 seq 1 name = enc(k-9, "Asha Kumar") -> reads "Asha Kumar"
erase  : DELETE key k-9 from the key store (events untouched, stream positions untouched)
after  : acct-9 seq 1 name = enc(k-9, ...)  -> cannot be decrypted; amounts and currency still replay   ✓

Land it Event sourcing is the right choice when the business needs the history, and an expensive way to store current state when it does not.

Likely follow-ups
"How do snapshots work, and what goes wrong with them?"

A snapshot is the aggregate's state after event N, stored alongside the stream. Loading the aggregate means reading the snapshot and replaying only events after N.

They are taken every few hundred events, or on a schedule, by a background process or opportunistically on load.

What goes wrong:

  • Second schema: the snapshot's format must be versioned. When the aggregate's fields change, old snapshots become unreadable, and the safe response is to discard them and replay from events, which must be possible.
  • Baked-in bug: a snapshot taken from a buggy version of the code bakes the bug into the state. Fixing it means invalidating snapshots and replaying, so snapshots carry the code version that produced them.
  • Stale snapshot: the snapshot can be stale relative to the stream if the event store and the snapshot store are written separately, which is the dual-write problem again.
snapshot rowruns offline
# illustrative output
snapshots: stream=acct-9 | as_of_seq=99,800 | code_version=3.2.0 | state={"balance":1204.50,...}
load: code_version 3.2.0 != running 3.3.0 -> discard snapshot, replay from seq 1, save a new snapshot   ✓

Snapshots are a cache, and they need every discipline a cache needs.

"How do you delete a person's data from an immutable log for a privacy request?"

Crypto-shredding is the workable answer. Every personal field in an event is encrypted with a key specific to that person, stored in a key store separate from the event store; the event stream holds ciphertext for names, addresses, and emails and plaintext for the non-personal fields.

Reading an event decrypts with the person's key.

An erasure request deletes the key. Every event that referenced that person becomes unreadable in its personal fields.

The stream, the offsets, and the non-personal facts stay intact, so replays and projections keep working with the personal fields absent.

key store versus event storeruns offline
# illustrative output
key store:   k-9 -> (deleted)
event store: seq 1 AccountOpened {"name": "Zm9v...", "currency":"EUR"}   name unreadable, currency readable
projection:  customer_view row for acct-9 must also be erased ✗ if it copied the plaintext name

The costs: a key-management system with its own availability and backup story, a decision per field about what counts as personal, and projections that must also erase the plaintext they had copied.

The alternative — rewriting the stream to remove events — breaks the append-only guarantee and every consumer's position, so it is a last resort.

"What is the cost in the team, not the technology?"

Every engineer has to think in events and in projections rather than in rows, and most have never done it.

Simple questions — what is this customer's current address — become "load the aggregate" or "query the projection", and a bug fix that would have been an UPDATE becomes a compensating event plus a projection rebuild.

Debugging means reading a stream of events and mentally replaying them, and the tooling for that is usually home-grown. Hiring becomes harder because the pool of engineers with the experience is small.

And the architecture is hard to leave: once the events are the source of truth, converting back to a conventional model is a migration of every aggregate.

I have seen teams spend their first year building the infrastructure — the store, snapshots, upcasters, projections, replay tooling — before shipping features that a conventional model would have shipped in a month. The domains where that pays off are real but narrow.

"When would you actually recommend event sourcing?"

When the history is the product.

A ledger where every balance must be explainable as a sequence of postings and auditors ask "how did this number arise"; a claims or approvals workflow where regulators require every state change with who and when; a trading or betting system where replaying the exact sequence of inputs is how disputes are resolved; or a collaborative document where the operations are the data.

In those, a conventional model would end up building an audit log that is a worse event store.

Even then I would apply it to the one aggregate that needs it — the ledger — and keep the rest of the service conventional, with the event-sourced aggregate publishing ordinary events for everyone else.

The test I use is whether the business would pay for the history if it cost a feature; if the answer is yes, event sourcing earns its keep, and if it is "it would be nice", it does not.

Q76 · Design. "A read model's projection logic has a bug and the table has been wrong for a month. Design a rebuild from the event history while the system stays live."

Reveal answer

Strong answer Requirements: the read model must be corrected from the source of truth; users keep reading throughout; no double-processing of live events with the replayed ones. Design, in steps.

  1. Check history: confirm the event history is available for the full period. Kafka retention covers it, or a compacted or archived topic does. If not, the rebuild must come from the owning services' databases instead, which is a different job.
  2. New group, new table: deploy the fixed projection code as a new consumer group with a new offset starting at the beginning of the topic, writing to a new table order_view_v2. The old consumer and table keep serving reads.
  3. Replay: let the new consumer replay history. At a million events an hour this is a matter of hours, and the new consumer's lag metric shows progress.
  4. Validate: when the new consumer's lag is near zero, compare a sample of rows between the two tables to validate the fix.
  5. Switch: switch reads to the new table with a feature flag or a view rename, then stop the old consumer and drop the old table.

Every projection consumer must be built for this from the start: idempotent, able to start from offset zero, and writing to a table named by version. Trade-offs: double storage and double consumption during the rebuild.

What I would not do is fix rows in place with a script, because the script will have its own bugs and the next rebuild is inevitable.

Picture it The two consumer groups and two tables at four moments of the rebuild, then one wrong row and its corrected twin (see the CQRS pattern).

The setup: topic orders.events has events up to offset 1,200,000 and the old projection has a discount bug.

The trace: the new group replays from offset 0 while the old one keeps serving.

rebuild timelineruns offline
# illustrative output
moment      head      group projection-v1 -> order_view (buggy)   group projection-v2 -> order_view_v2     reads served by
start       1,200,000 lag 0                                        offset 0, lag 1,200,000                  order_view
+3 h        1,203,000 lag 0                                        offset 1,100,000, lag 103,000            order_view
+3 h 40     1,203,700 lag 0                                        offset 1,203,650, lag 50                 order_view
cutover     1,203,710 paused, lag 0                                lag 0, compared, flag flipped            order_view_v2   ✓

What you see: the bug in one row, and the same row after the replay.

order 123 in each tableruns offline
# illustrative output
order_view     : order_id=123 | promo=SUMMER10 | total=49.90   ✗ discount not applied
order_view_v2  : order_id=123 | promo=SUMMER10 | total=44.91   ✓ matches the owning service

Why: a read model is derived data, so a second derivation from the same history into a second table replaces it without touching the first.

The fix: switch readers with a rename inside one transaction.

cutoverruns offline
BEGIN;
ALTER TABLE order_view    RENAME TO order_view_old;
ALTER TABLE order_view_v2 RENAME TO order_view;      -- ✅ FIX: instant; reverse the two renames to roll back
COMMIT;

Land it A read model is disposable by definition, so the rebuild is a second consumer into a second table and a switch, not a repair.

Likely follow-ups
"Kafka retention on the order topic is seven days. The bug is a month old. Now what?"

Then the topic is not the source of truth for the full period and I say so before starting. I have three options, in order of preference.

First, if the topic is log-compacted, the latest event per key is still there, and for a read model that only needs the current state per order that is enough to rebuild.

Second, if events are archived — a sink connector writing to object storage, or a tiered-storage configuration on Kafka 3.6 and later — I replay from the archive into a temporary topic and run the new consumer against that.

Third, if neither exists, the rebuild comes from the owning service's database. A one-off export job walks the orders table and emits synthetic events in the same shape, which the new projection consumes.

That last path is slower and needs the owning team's cooperation.

what each source still holdsruns offline
# illustrative output
topic retention 7 days : events from the last 7 days only; the bug is 30 days old   ✗
compacted topic        : latest event per order key -> enough for "current state" views   ✓
archive in object store: full history -> replay into a temporary topic   ✓
orders table export    : synthetic events, current state only, slower   (last resort)

The lesson I would write down afterwards is that retention on a topic that feeds read models must be at least as long as the longest rebuild you might ever need, or an archive must exist.

"While the replay is running, live events keep arriving. How does the new consumer not double-apply them, and how do you know when it has caught up?"

The new consumer group reads the topic from offset zero and keeps reading through to the live head, so the historical and the live events are one continuous stream to it; there is no separate live feed to merge.

Nothing is applied twice because each event has exactly one offset and the consumer visits each offset once.

Idempotency is still required, because a consumer crash mid-batch redelivers from the last committed offset, so the projection uses an upsert keyed by order id, and I store the last applied offset per partition in the read-model table.

Catch-up is a number, not a feeling: the consumer group's lag metric, which is the head offset minus the committed offset summed over partitions.

lag per partitionruns offline
# illustrative output
group projection-v2   partition  committed   head      lag
                      0          401,230     401,260   30
                      1          400,980     401,000   20
                      total lag 50   ✓ under a few hundred and staying there

When it is under a few hundred and staying there for several minutes, the new table is as current as the old one. I run the row comparison at that point, not before.

"How do you compare the two tables convincingly when the whole point is that the old one is wrong?"

I compare against expectations, not against the old table.

The bug affected a known set of rows — say discounts on orders with a specific promotion type — so first I check that the new table differs from the old exactly on that set and nowhere else.

A query that joins the two tables on order id and counts mismatches grouped by promotion type shows that directly.

mismatch queryruns offline
SELECT o.promo_type, count(*) AS mismatches
  FROM order_view o JOIN order_view_v2 n USING (order_id)
 WHERE o.total IS DISTINCT FROM n.total
 GROUP BY o.promo_type;
-- Result (illustrative): SUMMER10 | 18,204 and nothing else ✓ differences only where the bug was

If there are mismatches outside the expected set, either my understanding of the bug is incomplete or the projection has a second bug, and I stop and look.

Then I take a random sample of a few hundred rows and recompute the expected value by hand from the events, or from the owning service's database, which is the real oracle.

Finally I run the replay determinism test: replay the same window twice into two scratch tables and confirm they are byte-for-byte identical. Only then do I switch reads.

"The requirement changes: reads must not be stale by more than a second during the switch. Does your design still work?"

Mostly, with one change to the cutover step. A feature flag or view rename switches reads instantly, so staleness at the switch moment is just the new consumer's lag, which I have already driven to near zero.

The risk is a brief window where a write landed in the old table after the new consumer's last commit.

To close it I do a short sequence:

  1. Pause the old consumer.
  2. Wait for the new consumer's lag to reach zero on every partition.
  3. Flip the flag.

The pause is a few seconds, and during it the old table simply stops updating, which is within a second of staleness only if the flip is fast.

If even that is not acceptable, I run both consumers until the flip and accept that the two tables may disagree for under a second.

What I cannot promise is zero staleness with a rebuild that took hours, so I would push back on a one-second requirement for the rebuild itself and hold it only for the switch.

"You have a day, not a week. What do you cut?"

I cut the comparison tooling and the graceful cutover, not the second table. Under time pressure I still refuse to patch rows in place, because that is the option that creates the next incident.

I deploy the fixed consumer as a new group writing to order_view_v2, replay, and instead of a full reconciliation I check the hundred rows support flagged plus a random fifty.

The switch is a single database view rename inside a transaction, which is instantaneous and reversible with the reverse rename.

What I skip is the automated determinism test, the dashboards for replay progress, and the careful decommission of the old table — I leave the old consumer running for a day as a fallback, then delete it.

I also write down what I skipped as a ticket, because the next rebuild will happen and the tooling I cut is what makes it a routine rather than a scramble.

Q77. "How do you version events over years, and what is an upcaster?"

Reveal answer

Strong answer Events, once written, are read for as long as the topic or event store retains them, so a change to an event's shape has to be readable against every version that still exists.

The first rule is to prefer additive changes: add optional fields with defaults, never rename, never change a type, never reuse a field. A schema registry with backward-compatibility checking enforces this in the pipeline.

When a change cannot be additive — a field's meaning changed, or two fields merged — the event type gets a version number.

The consumer then runs an upcaster: a small function that takes an event of version 1 and produces the equivalent event of version 2.

It is applied on read, before the business logic sees the event, so the logic only ever handles the newest shape.

Upcasters chain (v1 to v2 to v3) and stay in the codebase for as long as v1 events can still be read, which for an event-sourced aggregate is forever.

Two habits limit the pain: keep events small and specific so each one changes rarely, and for a truly breaking redesign publish to a new topic and migrate consumers rather than upcasting a whole stream.

As a matter of ownership, the producing team maintains the upcasters and publishes them in a shared library, so twenty consumers do not each write their own.

Picture it One OrderPlaced event type stored in three versions on the topic, and what the consumer and an in-place rename each do to it.

The setup: the producer first wrote total as a decimal, later moved to amountCents plus currency (v2), later added channel (v3). Each change gets an upcaster.

V1toV2 upcasterruns offline
class V1toV2 implements Upcaster {
  public int from() { return 1; }
  public JsonNode apply(JsonNode e) {
    ObjectNode n = ((ObjectNode) e).deepCopy();
    long cents = Math.round(n.get("total").asDouble() * 100);
    n.remove("total");
    n.put("amountCents", cents).put("currency", "EUR");   // assumption: v1 was always EUR
    n.put("version", 2);
    return n;
  }
}
JsonNode toCurrent(JsonNode e) {              // runs in the consumer's deserialiser
  int v = e.path("version").asInt(1);
  while (v < CURRENT) { e = chain.get(v).apply(e); v++; }
  return e;
}

Make the invisible visible: the topic holds every version side by side, and only the read path converts them.

topic and read pathruns offline
# illustrative output
topic order-events (stored bytes, never rewritten)
offset  version  payload
  101      1     {"orderId":"o-77","total":19.90}
  482      2     {"orderId":"o-91","amountCents":2450,"currency":"EUR"}
  903      3     {"orderId":"o-95","amountCents":900,"currency":"EUR","channel":"web"}

consumer deserialiser:  v1 --V1toV2--> v2 --V2toV3--> v3 --> handler (sees v3 only)

The trace: reading offset 101 through the chain.

upcast traceruns offline
read offset 101: version=1
  ✓ V1toV2: total 19.90 -> amountCents 1990, currency EUR, version 2
  ✓ V2toV3: channel absent -> "web", version 3
  ✓ handler receives a v3 event
# TRAP: the producer renames total -> amountCents in place, no version, no upcaster
read offset 482 with the old consumer:
  ✗ e.get("total") is null -> NullPointerException (path("total").asDouble() would give a silent 0.0)

Why: a rename looks like a removal to every reader that has not upgraded, and an old consumer cannot tell "absent" from "zero".

The fix: add the new field and keep the old one populated for a deprecation window; use an upcaster only for changes that cannot be additive. For aggregates rebuilt from events see Pattern: Event Sourcing.

what the consumers see nowruns offline
# illustrative output
{"orderId":"o-91","total":24.50,"amountCents":2450,"currency":"EUR"}
  old consumer  reads total        -> 24.50 ✓
  new consumer  reads amountCents  -> 2450  ✓

Land it Additive changes are free and everything else is an upcaster you keep forever, so I design events to change by addition.

Likely follow-ups
"Which schema registry compatibility mode do you set, and what does each one actually check?"

For event topics I set BACKWARD_TRANSITIVE on the subject. Backward compatibility means a consumer using the new schema can read data written with the old schema, which is what matters when consumers upgrade before producers or replay old data.

Concretely the registry rejects a new schema version that removes a field without a default or adds a required field without a default.

The transitive variant checks against every earlier version, not just the previous one, which matters because a replay from offset zero meets every version that ever existed.

FORWARD is the reverse — old consumers can read new data — and is what you want when producers upgrade first. FULL_TRANSITIVE demands both, which is the safest and is what I use on topics with long retention and many consumers.

The check runs in the producer's pipeline against the registry's /compatibility endpoint before the schema is registered, so an incompatible change fails the build rather than the consumers.

registry compatibility checkruns offline
# illustrative output
POST /compatibility/subjects/order-events-value/versions/latest
  new schema drops "currency" (no default)
  200 {"is_compatible": false}     ✗ pipeline fails before anything is registered
"Where does the upcaster run — producer side, consumer side, or in the broker?"

Consumer side, on read, and never in the broker. The broker stores bytes and knows nothing about meaning, and rewriting stored events would destroy the audit history that event sourcing exists to keep. The producer cannot upcast either, because the old events are already written.

So the deserialisation layer in the consumer holds the chain: it reads the version field from the envelope, looks up the upcasters from that version to the current one, and applies them in sequence before handing the object to the handler.

In Spring Kafka I do this in a custom Deserializer or a RecordInterceptor so the handler code only ever sees the current shape. The producing team publishes the upcasters as a small versioned library, and a consumer that upgrades the library gets the new chain.

Frameworks such as Axon call this an EventUpcaster and run it in exactly this position.

"Why not just change the field in place and bump the version in the payload?"

Because changing a field in place breaks every reader that has not upgraded yet, and in a platform with twenty consumers there is always one that has not.

A rename looks like a removal to the old consumer, so a field it reads is suddenly absent, and it either throws or silently treats the value as null, which is worse.

Bumping a version number in the payload does not help those consumers; it just tells them they are about to fail. The additive rule exists so that the old and the new readers can both parse every event during the weeks the migration takes.

If the meaning of a field has genuinely changed, adding a new field with the new meaning and leaving the old one populated for a deprecation window is additive, and a registry with backward compatibility enforces that.

The in-place change is only safe when there is exactly one consumer and you control its deploy, which is rare enough that I do not rely on it.

"How do you eventually get rid of a five-year-old upcaster chain?"

By snapshotting, which is the only way to make old versions unreadable without losing them. For an event-sourced aggregate, a snapshot is a stored materialisation of the aggregate's state at a given sequence number, so loading it needs only the snapshot plus events after it.

Once every aggregate has a snapshot taken after version 3 was introduced, no live code path reads version 1 or 2 events, and the upcasters for those versions can be deleted from the library.

The old events stay in the store for audit and can still be read by a one-off tool that keeps the old chain.

For a plain Kafka topic the equivalent is retention: when no event older than the version 3 introduction still exists in the topic or in any archive that a consumer might replay from, the chain shrinks.

I record the earliest version still present per topic as a metric, so the deletion is driven by evidence.

Q78 · Scenario. "A projection consumer was replayed from the start to rebuild a read model, and the rebuilt table differs from the original in about 1% of rows — some discounts differ. No code changed. Why?"

Reveal answer

Strong answer The symptom — the same code and the same events producing different output — means the projection is not a pure function of the events.

Evidence: pick a differing row, find the events that built it, and run the projection by hand to see which input is not in the events.

Causes ranked:

  1. A changed lookup: the projection calls a pricing or promotion service to compute the discount, and the promotion that was live a month ago is not live today.
  2. The wall clock: it uses the current time, so "is this order within the 30-day window" evaluates differently on replay.
  3. Another read model: it reads a read model that is itself at a different point in time.

All of these are the same mistake: state that belonged in the event was looked up instead. The fix has two parts.

For the rebuild, reconstruct the historical inputs — replay the promotion events alongside, or snapshot the promotions table as of each event's timestamp — accepting that a perfect rebuild may not be possible for this month.

For the future, make projections deterministic: every fact the projection needs travels inside the event (event-carried state transfer), and any time-based logic uses the event's timestamp, never now().

Prevention: a test that replays a fixed event set twice and asserts identical output, run in CI for every projection.

Picture it Order o-1041 as the projection built it a month ago and as the replay builds it today, with the one lookup that changed in between.

The setup: the projection computes the discount by calling the pricing service instead of reading it from the event.

impure vs pure projectionruns offline
void on(OrderPlaced e) {
  // ❌ TRAP: asks pricing "what is the discount now?" - the answer depends on today's promotions
  BigDecimal d = pricing.discountFor(e.orderId(), e.items());
  // ✅ FIX: use what the event recorded at the moment of the order
  // BigDecimal d = e.discountApplied();
  view.save(new OrderView(e.orderId(), e.total().subtract(d)));
}

Make the invisible visible: the same event, two different answers, because the input that differs is not in the event.

table state before and after replayruns offline
# illustrative output
event  o-1041 OrderPlaced total=100.00 items=[sku-9]  (no discount field)

order_view built 30 days ago           order_view rebuilt today
o-1041  net=90.00   (SPRING10 live)     o-1041  net=100.00  (promo ended)
o-1042  net=50.00   (no promo)          o-1042  net=50.00             ✓ same
o-1043  net=72.00   (SPRING10 live)     o-1043  net=80.00             ✗ differs  (about 1% of rows)

The trace: a recording stub around the projection shows the hidden input.

stub log for o-1041runs offline
replay o-1041
  ✓ read event OrderPlaced
  ✗ HTTP GET pricing/discounts?order=o-1041   <- not in the event list
  ✗ Instant.now()                             <- wall clock

Why: the projection is not a pure function of the events, so replay cannot reproduce history.

The fix: carry the discount in the event and use the event timestamp; then the rebuild matches.

after the fixruns offline
order_view rebuilt twice from the same events
  hash run 1: 9c1f...   hash run 2: 9c1f...   ✓ identical

Land it A projection that reads the outside world is not replayable, and the replay test is the cheapest way to find out before the rebuild you actually need.

Likely follow-ups
"How do you find which input is impure without reading every line of the projection?"

I start from one differing row and work backwards with the trace, not the code.

I take the order id, pull the events for that key from the topic, and run the projection against them in a test harness with a recording stub around every external call.

Anything the projection reaches for that is not in the event list shows up in the stub log: an HTTP call to pricing, a JDBC read from a promotions table, a call to Instant.now() or LocalDate.now().

I also grep the projection module for the obvious signatures — now(), RestClient, @Autowired repositories that are not the read model's own — which takes two minutes and usually finds it.

If the harness and the grep both come up empty, I check for nondeterministic iteration: a HashMap whose order decides which discount wins, or a query without ORDER BY feeding a "first match" rule.

That last one is the case that fools people, because the code looks pure.

"You cannot reconstruct last month's promotions. What do you tell the business?"

I tell them that the rebuilt table is correct for what the events say, and that the 1% of rows that differ reflect a fact we did not record: which promotion was live at the moment each order was placed.

Then I give them the choice, because it is a business call. Option one: keep the original table's values for those rows, because they were computed at the time with the live promotions and are therefore the historically accurate figures.

Option two: accept the rebuilt values and reprocess any refunds or reports that depend on them.

I would recommend option one and implement it as a one-off merge: copy the discount column for the affected rows from the old table into the new one, log which rows were merged, and keep the old table for audit.

What I would not do is quietly pick one and hope no one reconciles it against finance later.

"Doesn't putting everything the projection needs inside the event make the events huge?"

It makes them bigger, and that is a real cost I would size rather than dismiss. The rule is not "put everything in", it is "put in what a consumer needs to make a decision without asking anyone".

For an order event that means the price actually charged, the discount actually applied, and the promotion id, which is a few hundred bytes, not the entire product catalogue.

Events that carry state this way are called event-carried state transfer, and the alternative — a thin event with an id and a lookup — is what produced this bug.

At a million events an hour, an extra 500 bytes is about 12 gigabytes a day across the topic, which Kafka handles without noticing but which does show up in retention costs.

When a consumer genuinely needs a large reference dataset, the right move is for that consumer to maintain its own local copy fed by that dataset's own events, keyed by time, so a replay can look up the value as of the event's timestamp.

"Describe the replay test you would put in CI precisely."

It is a single JUnit test in the projection module.

It loads a fixed event set from a file — a few thousand events covering every event type, checked into the repository — and runs the projection twice from an empty in-memory or Testcontainers database, with the clock injected as a fixed Clock.

After each run it exports the read-model table sorted by primary key and computes a hash. The assertion is that the two hashes are equal.

A second assertion compares the hash against a golden value stored in the repository, so a change in projection behaviour has to update the golden file deliberately in the same pull request, which makes behaviour changes visible in review.

The test fails if the projection touches the network, because the test profile registers no HTTP client bean and any attempt to call one throws. It runs in under thirty seconds and it is the cheapest guarantee of replayability I know.

replay testruns offline
@Test void replayIsDeterministic() {
  List<Event> events = load("events-fixed.jsonl");
  String h1 = hash(runProjection(events, fixedClock));
  String h2 = hash(runProjection(events, fixedClock));
  assertEquals(h1, h2);                 // ✅ no hidden input
  assertEquals(readGolden(), h1);       // behaviour changes must update the golden file in the PR
}

Q79. "Connect this to Chapter E8: under READ COMMITTED, can an outbox poller ordering by an identity column miss a row? Explain the gap and the fix."

Reveal answer

Strong answer Yes, and it is a subtle one. An identity or sequence value is assigned when the row is inserted, but the row becomes visible when its transaction commits, and those happen in different orders.

Transaction A inserts outbox row 100 and is slow to commit; transaction B inserts row 101 and commits immediately.

The poller, tracking "last sequence published = 99", selects rows above 99, sees only 101 (100 is not yet visible under READ COMMITTED, as Chapter E8 explains), publishes it, and records 101 as its high-water mark.

Then A commits: row 100 is now visible but below the mark, and the poller never publishes it.

The fixes, from simplest to most robust:

  1. Per-row flag: track publication per row with a published_at column and a partial index on the null ones, rather than a high-water mark, so visibility order does not matter.
  2. Mark with a grace period: if a mark is needed for ordering, only advance it past a gap after a grace period longer than any transaction could take, which is fragile.
  3. Change data capture: it reads the log in commit order and has no gap at all.

The same issue affects any "process everything after id N" job on any table, which makes it a good general interview point about MVCC.

Picture it Two database sessions and a poller with a high-water mark, step by step, with the outbox table as the poller sees it. See also Pattern: Outbox.

The setup: the poller remembers the last id it published and asks for everything above it.

poller with a markruns offline
-- ❌ TRAP: remembers a position; mark is 99
SELECT id, payload FROM outbox WHERE id > 99 ORDER BY id LIMIT 500;

Make the invisible visible: ids are handed out at INSERT time, rows become visible at COMMIT time.

outbox table after step 3runs offline
outbox            committed?     visible to the poller?
id=99   o-60      yes            yes (already published)
id=100  o-61      NO (A open)    no
id=101  o-62      yes            yes
poller mark: 99 -> reads id > 99 -> gets only 101 -> mark becomes 101

The trace: time-ordered steps; step 5 is where the row is lost.

interleavingruns offline
step  session A                B                    poller (mark)
1     BEGIN; INSERT -> id 100
2                              INSERT -> id 101; COMMIT
3                                                   id > 99  -> [101]  ✓ publish, mark = 101
4     COMMIT (100 visible)
5                                                   id > 101 -> []     ✗ row 100 never published

What you see: a reconciliation query finds a committed row below the mark.

consoleruns offline
-- # illustrative output
SELECT id FROM outbox WHERE published_at IS NULL AND id < 101;
 id
-----
 100

Why: sequence order is insert order, visibility is commit order.

The fix: track publication per row, not a position.

per-row pollerruns offline
-- ✅ FIX: no remembered position, so commit order does not matter
SELECT id, payload FROM outbox
 WHERE published_at IS NULL ORDER BY id LIMIT 500 FOR UPDATE SKIP LOCKED;

What you see now: row 100 is selected as soon as it is committed.

trace after the fixruns offline
step 3  published_at IS NULL -> [101]  ✓ published
step 5  published_at IS NULL -> [100]  ✓ published (late, but not lost)

Land it Sequence order is insert order and visibility is commit order, so a poller that tracks a high-water mark will eventually skip a row, and a per-row flag or the log itself avoids that.

Likely follow-ups
"Show me the per-row query and its index, and why it does not have the same gap."

The poller runs SELECT id, payload FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT 500 FOR UPDATE SKIP LOCKED.

The index is partial: CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL, so it only ever contains the few rows still waiting and stays tiny no matter how large the table grows. There is no gap because the poller is not remembering a position.

Row 100, which committed late, is simply a row whose published_at is null, and the next poll selects it like any other.

Commit order no longer matters, because visibility is the only thing the query depends on, and a row is visible exactly when it is committed.

The cost is one update per published row to set published_at, which is why I batch the update by id list after a successful send. SKIP LOCKED lets several poller instances share the table without blocking each other.

"With the per-row flag, is publication order still guaranteed?"

Not globally, and I say that plainly. Two events for different orders can now be published in an order that differs from their sequence, because row 100 may be picked up after row 101.

What matters is order per key, and I protect that in two places. First, the poller orders its batch by id, so within one batch rows go out in sequence order.

Second, and more importantly, Kafka's producer preserves order per partition.

That holds when enable.idempotence=true and max.in.flight.requests.per.connection is 5 or fewer.

The key is the order id, so all events for one order land on one partition in the order the poller sent them.

The remaining case is two events for the same order in two different transactions where the first commits after the second; that is a problem in the writer, not the poller, and it is prevented by the aggregate's own version check when the second transaction ran.

"How would you prove this gap exists rather than just argue it?"

With two sessions and a poller in a test. Session A does BEGIN; INSERT INTO outbox ... RETURNING id; and stops without committing; it gets id 100. Session B inserts and commits, getting id 101.

Now run the poller once with a high-water mark of 99: it selects WHERE id > 99, sees only 101, and sets its mark to 101. Commit session A. Run the poller again: WHERE id > 101 returns nothing, and row 100 is never published.

That is a five-line test with Testcontainers and two Connection objects, and I would keep it in the repository as the reason the code looks the way it does.

In production the evidence is quieter: a reconciliation between the outbox table and the topic that finds rows with an old id, published_at null, and a mark already past them.

"Does the same gap exist with Debezium, and why or why not?"

It does not, because Debezium does not query the table at all. It reads the PostgreSQL write-ahead log through a logical replication slot, and the log records transactions in commit order, not in insert order.

Transaction A's insert of row 100 appears in the log at the position where A committed, which is after B's commit, so Debezium emits 101 then 100, and both are emitted exactly once. The sequence value is irrelevant to it.

The trade-off is what the outbox chapter covered: a replication slot pins the write-ahead log until the connector consumes it, so an unattended slot fills the disk, and Debezium needs its own monitoring.

But on this specific question — can a row be skipped — the log-based approach is the one with no gap by construction, which is the main reason I prefer it over polling when a team can operate a connector.

Q80 · Design. "A nine-step fulfilment saga is choreographed across seven services and nobody can change it safely. Design the migration to orchestration without stopping fulfilment."

Reveal answer

Strong answer Assumptions: thousands of sagas are in flight at any moment; the seven services keep their current events; the migration must be reversible. Design in four phases.

  1. Phase one, map: write down every event each service consumes and emits as the state machine the orchestrator will run; this document is the contract.
  2. Phase two, shadow: build the orchestrator inside the fulfilment service (or Temporal, at this size). It consumes the same events, tracks where every saga is, and compares its expected next event with what actually happens, emitting a metric on disagreements. This validates the state machine against reality for a couple of weeks without sending any commands.
  3. Phase three, switch step by step: the orchestrator begins issuing the command for step four instead of waiting for the step-three event to trigger it. The step-four handler first becomes idempotent to both the old event trigger and the new command, and when it is stable the event trigger is removed.
  4. In-flight sagas: new sagas start under the orchestrator, in-flight sagas finish under choreography, and a flag on the saga row tells them apart.
  5. Phase four, clean up: once all nine steps are commanded, delete the choreography subscriptions.

Trade-offs: weeks of dual paths and idempotency work in every participant.

What I would not do is a cutover where in-flight sagas are converted mid-way; the two mechanisms disagree about state, and the conversion will strand orders.

Picture it The nine saga steps of the running order flow during the migration: who triggers each step in each phase, and what the saga row and a participant guard table hold. See Pattern: Saga choreography and Pattern: Saga orchestration.

Make the invisible visible: one row per phase, one column per step; E means the previous step's event triggers it, B means event and command are both live, C means only the orchestrator command.

trigger per step and phaseruns offline
step               1  2  3  4  5  6  7  8  9
today              E  E  E  E  E  E  E  E  E
phase 2 (shadow)   E  E  E  E  E  E  E  E  E   orchestrator only watches
phase 3, week 1    E  E  E  B  E  E  E  E  E   step 4 handler accepts both
phase 3, week 2    E  E  E  C  B  E  E  E  E   step 4 event trigger removed
phase 4            C  C  C  C  C  C  C  C  C   choreography subscriptions deleted

The setup: the saga row says which mechanism owns each saga, and each participant guards its step with a unique key.

saga row and guard tableruns offline
-- saga (fulfilment service)                 -- guard (payment service)
-- saga_id  mode           step  version      CREATE TABLE step_executions (
-- s-9001   choreography   5     1              saga_id text, step_name text, result jsonb,
-- s-9002   orchestrated   4     1              PRIMARY KEY (saga_id, step_name));

The trace: during phase 3 week 1 the same step arrives twice for an orchestrated saga.

dual trigger on step 4runs offline
s-9002 take_payment
  t0 event StockReserved arrives   -> INSERT step_executions ✓ -> charge card, emit PaymentTaken
  t1 command TakePayment arrives   -> INSERT step_executions ✗ unique violation
                                      -> return stored result, no second charge

What you see: without the guard the same overlap is a double charge; with it, one row.

payments tableruns offline
# illustrative output
without guard                          with guard
payments for s-9002: 2 rows  ✗         payments for s-9002: 1 row  ✓

Land it Shadow first, then command one step at a time while in-flight sagas finish the old way — a saga migration is itself a saga, and it needs the same care.

Likely follow-ups
"Shadow mode has been running for two weeks and it disagrees with reality on 3% of sagas. What does that tell you?"

It tells me my state machine is wrong or reality is wrong, and I need to know which before I command anything. I take the disagreements and group them by where they diverge. Usually there are two or three clusters.

shadow disagreementsruns offline
# illustrative output
shadow mode, 14 days: 3.0% of sagas disagree
  cluster A  partial-shipment path missing from the map     1.9%  -> extend the state machine
  cluster B  compensation running after the pivot (a bug)   0.8%  -> ticket
  cluster C  unexplained                                    0.3%  -> must reach 0 before phase 3

One cluster is undocumented behaviour: a service emits an event the mapping did not know about, such as a partial-shipment path that only fires for multi-warehouse orders. That is my state machine being incomplete, and I extend it.

Another cluster is genuine bugs in the choreography: a step firing twice, or a compensation that runs after the pivot. Those are real defects in production today, and I ticket them separately, because the orchestrator will fix them by design once it is in command.

The rule I hold is that shadow mode must reach well under 0.1% disagreement, all of it explained, before phase three starts. Three percent unexplained means I do not understand the process I am about to take over.

"Why one step at a time rather than switching the whole chain for new sagas only?"

Because switching the whole chain for new sagas still requires every one of the seven services to accept commands correctly at once, and if any one of them has a subtle difference between its event trigger and its command handler, every new saga breaks at that step on the same day.

One step at a time means the blast radius of a mistake is one step, and the rollback is one flag.

It also lets the participant teams do the idempotency work on their own schedule, which is what makes this a migration a real organisation can run rather than a coordinated deploy in disguise. The cost is a longer dual-running period.

If the organisation could genuinely deploy all seven at once and had a strong shadow-mode result, I would consider switching new sagas whole, but I would still keep in-flight sagas on the old path, because converting them is where orders get stranded.

"How does a participant handler become idempotent to both the old event and the new command?"

Both paths converge on one idempotent operation keyed by saga id and step. The service keeps a step_executions table with a unique key on (saga_id, step_name).

The event handler and the command handler both call the same internal method, which first tries to insert that row in the same transaction as the step's work.

If the insert hits the unique constraint, the step has already run, and the handler returns the stored result without redoing anything. So during the overlap, whichever trigger arrives first does the work and whichever arrives second is a no-op.

The result event the step emits is the same regardless of trigger, so downstream services cannot tell the difference. Once the event trigger is removed, the table stays, because the orchestrator itself may retry a command after a timeout. The extra insert costs a few milliseconds per step.

"The requirement changes: fulfilment needs a new tenth step next month. Do you wait for the migration?"

No, and this is actually the argument for the migration. I add the tenth step to the orchestrator's state machine and command it from day one, even while the earlier steps are still choreographed.

The orchestrator is already tracking every saga in shadow mode, so it knows when step nine completes for each saga, and it can issue the step-ten command at that moment.

The new service that handles step ten is built only as a command handler with the idempotency table, never as an event subscriber, so it does not add to the choreography I am dismantling.

In-flight sagas that started before the step existed are handled by a version field on the saga row: version 1 sagas end at step nine, version 2 at step ten.

That is exactly the kind of change nobody could make safely under choreography, and doing it this way demonstrates the payoff to the teams before the migration is finished.

"What would you cut under time pressure?"

I would cut the length of shadow mode and the per-step granularity, but not the idempotency work or the split between new and in-flight sagas.

Shadow mode could run one week instead of two, on the condition that the disagreement rate is under 0.1% and the busiest three paths are covered.

Steps could be switched in groups of three rather than one at a time, where the three are owned by the same team.

I would also defer building the orchestrator on Temporal and start with a state machine inside the fulfilment service using the saga table, because Temporal is a platform to operate and I can move to it later.

What I keep at any cost: the guard table in every participant, because without it dual running duplicates side effects, and the rule that in-flight sagas finish under the mechanism that started them.

Those two are what make the migration reversible, and reversibility is the thing I refuse to trade for speed.

09 · DrillResilience, Observability, Testing & Deployment — Q81–Q115

Architecture is what you draw; operability is what you live with. These thirty-five questions are weighted toward scenarios because that is how senior rounds probe them: a platform that fell over from one slow dependency, a trace with forty hops, a deploy that broke someone else's consumers. The design questions ask for the machinery — objectives, alerts, canaries, contracts, service identity — that lets many teams change many services without breaking each other.

Drill · Resilience under load

These questions test whether you can see the feedback loops that turn a local fault into a platform outage, and cut them in the right place.

Q81. "Describe the anatomy of a cascading failure. What are the feedback loops, and where do you cut them?"

Reveal answer

Strong answer A cascading failure is a local fault that spreads because each component's reaction makes the fault worse. It starts with one slow or failing dependency.

  1. Queueing: callers wait on the slow dependency, their thread pools fill, and their own callers start waiting, so the slowness travels upstream hop by hop. Cut: timeouts and bulkheads, so a slow dependency can take only a bounded share of the caller.
  2. Retries: callers time out and retry, multiplying the load on the dependency exactly when it can least afford it. Cut: retry budgets, jitter, and breakers that stop calling.
  3. Health checks: instances that report unhealthy because a dependency is slow get pulled from rotation, concentrating the same traffic on fewer instances, which then fail faster. Cut: shallow readiness checks that test the instance itself, not its dependencies.
  4. Recovery: when the dependency comes back, the accumulated backlog of retries arrives as a wave and knocks it over again. Cut: load shedding on the dependency and slow half-open probing from breakers.

The goal is a system that degrades in steps rather than falling off a cliff.

Picture it One slow dependency of the product page, with the retry multiplication, the pool filling and the blast radius, each in numbers. Cuts live in Timeout, Retry, Circuit breaker, Bulkhead and Load shedding.

Make the invisible visible: who waits on whom, and what the failure reaches.

topology and blast radiusruns offline
Gateway --> ProductPage --> Recommendations   ✗ slow (6 s instead of 40 ms)
   |            |
   |            +-- threads parked here (loop 1), retried here (loop 2)
   +-- deep health check pulls ProductPage pods (loop 3); Checkout on the same gateway goes too

The trace: retry multiplication through three layers that each retry three times.

request rate through retriesruns offline
layer          attempts   calls reaching Recommendations per user request
Gateway        3          3
ProductPage    3          3 x 3 = 9
RecsClient     3          9 x 3 = 27
100 user requests/s  ->  2,700 calls/s into a service that was fine at 100/s  ✗
one 10% retry budget at the client nearest the dependency, none above: 100 -> ~110/s  ✓

What you see: ProductPage pool occupancy and ready pods at four moments.

capacity over timeruns offline
# illustrative output
moment    pool (200)            Recs latency   ready pods
t=0 s      8 busy                   40 ms        6/6
t=20 s   140 busy                6,000 ms        6/6
t=60 s   200 busy, 300 queued    timeouts        2/6   (probes time out, pods removed)
t=90 s   200 busy on 2 pods      timeouts        0/6   loop 4: recovery wave will knock it over again

Land it A cascade is four feedback loops, and a resilient platform has a deliberate cut in each one before the incident, not after.

Likely follow-ups
"Pick the single most valuable cut if you could only make one. Why that one?"

The timeout, because it is the cut that every other cut depends on.

Without a timeout a slow dependency parks the caller's threads indefinitely, so a bulkhead fills and stays full, a circuit breaker never sees a failure to count, and a retry budget never gets a chance to refuse.

With a timeout every waiting thread is released within a bounded time, so the service's capacity is reduced rather than removed. It is also the cheapest: a single number on the client. The number matters, though.

I set it from the dependency's measured p99 with a margin, not from a guess, and I set it on both the connect and the read phase, because a connect timeout alone does nothing once the connection is open.

If I were allowed a second cut, it would be the shallow readiness check, because health-check amplification is the loop that turns "half the capacity" into "no capacity".

"Retries make it worse — so should you never retry?"

You should retry when the failure is likely transient and the retry is bounded, and you should never retry when the dependency is already saturated. The problem is telling those apart at the moment of failure. Two mechanisms do it.

A retry budget caps retries as a fraction of primary requests — Envoy's default is 20% and Google's guidance is 10% — so that under widespread failure retries add at most a tenth to the load instead of doubling it.

retry budget arithmeticruns offline
100 primary requests/s, 3 attempts each, no budget      -> up to 300 calls/s  ✗
100 primary requests/s, retry budget 10%                -> at most 100 + 10 = 110 calls/s  ✓

A circuit breaker stops retries entirely once the failure rate crosses a threshold, because at that point the dependency needs less traffic, not more.

Within those limits, one retry with jittered backoff on connection errors and on 503 responses is worthwhile, and no retry on 4xx or on a read timeout for a non-idempotent call.

What I remove is the naive "retry three times immediately" that libraries ship as a default; that is the multiplier that turns a slowdown into a collapse.

"How would you tell, in the middle of an incident, which loop you are in?"

Each loop has a signature on a dashboard. Queueing shows as thread-pool active count at its maximum and rising latency at every upstream hop in sequence, with the earliest rise at the dependency.

Retry amplification shows as the dependency's request rate rising while user traffic at the gateway is flat — a 2× or 3× ratio between the two is retries.

Health-check amplification shows as the number of ready endpoints for a service falling while the pods themselves are running, with error rates on the survivors climbing in step. The recovery wave shows as a sawtooth: the dependency recovers, request rate spikes, it fails again.

I look at those four panels in that order. The one I check first is the ratio of downstream request rate to gateway request rate, because retry amplification is the loop that responds fastest to intervention: turning retries off with a flag gives immediate relief.

"What breaks at ten times the scale that does not break today?"

At ten times the scale the loops close faster than a human can react, so anything that relies on an engineer noticing and flipping a switch stops working. Thread pools that took two minutes to fill take ten seconds.

A retry storm that was 2× becomes 2× on a base that is already ten times larger, so the dependency is overwhelmed before its autoscaler wakes up. Health-check amplification becomes total in one probe cycle.

The controls that scale are the automatic ones: adaptive concurrency limits that shrink admission when latency rises without a human, breakers with short windows, and load shedding at the edge that sheds by priority.

The other thing that breaks is shared infrastructure: at ten times the load, a single Redis cluster or a single Kafka cluster shared by every service becomes the dependency everything cascades through, so I would partition those by domain long before that point.

Q82 · Scenario. "The recommendations service — a 'nice to have' widget — got slow for twenty minutes, and the entire storefront went down. Post-mortem: walk me through what happened and every change you would make."

Reveal answer

The real test Whether you can reconstruct the chain from a non-critical dependency to total outage and name the missing control at each link.

Strong answer Evidence I would gather: recommendations' latency graph, the product-page service's thread-pool active count and its HTTP client configuration, gateway error rates, and a thread dump if one was taken.

The likely chain:

  1. The product page called recommendations synchronously on every render, with a long or missing read timeout.
  2. Each call parked a thread for seconds, and within a minute all threads were parked.
  3. The product page stopped answering the gateway.
  4. The gateway's deep health check marked it unhealthy and removed instances.
  5. Checkout, which shares the gateway and perhaps the same pods, went with it.

Nothing crashed — the platform was brought down by waiting. Changes, in priority order.

  • On the product page: a 300-millisecond read timeout on the recommendations client; a bulkhead of perhaps 10% of the pool; a circuit breaker with a fallback that renders the page without the widget.
  • On the gateway: shallow health checks that never pull a service for a dependency's slowness.
  • On the platform: a template where every outbound client has a timeout by default, and a rule that a non-critical dependency must have a fallback that is exercised in tests.

Prevention beyond code: a game day where recommendations is deliberately slowed in staging and the storefront is expected to stay up; and a dependency classification — critical or degradable — written down for every call.

Picture it The twenty-minute outage as a timeline from the recommendations widget to the storefront, then the same minute with the three missing controls. See Timeout, Bulkhead, Circuit breaker and Health checks.

The trace: each row is the first moment a control was missing.

post-mortem timelineruns offline
# illustrative output
12:00:00  Recommendations p99 40 ms -> 6,000 ms
12:00:05  ProductPage: 200 req/s x 6 s = 1,200 calls wanted, pool 200   ✗ no read timeout
12:01:00  ProductPage pool 200/200 parked, widget call and everything else wait   ✗ no bulkhead
12:01:30  Gateway deep health check on ProductPage times out -> pods removed       ✗ deep check
12:02:00  Checkout shares the gateway and pods -> 502 for the whole storefront

What you see: a thread dump of the product page during the slowdown.

thread dump excerptruns offline
# illustrative output
"http-nio-8080-exec-87" RUNNABLE
  at java.base/sun.nio.ch.NioSocketImpl.read
  at ...RestClient.retrieve ... RecommendationsClient.fetch(RecommendationsClient.java:41)
  at ...ProductPageController.render
(197 more threads in the same frame)

The fix: a timeout, a bulkhead and a fallback on the recommendations client.

client with the three controlsruns offline
JdkClientHttpRequestFactory f = new JdkClientHttpRequestFactory();
f.setReadTimeout(Duration.ofMillis(300));                         // ✅ FIX: timeout
@Bulkhead(name = "recs")                                          // ✅ FIX: ~20 permits of 200
@CircuitBreaker(name = "recs", fallbackMethod = "noWidget")      // ✅ FIX: breaker + fallback
List<Item> recommendations(String userId) { return client.fetch(userId); }
List<Item> noWidget(String userId, Throwable t) { return List.of(); }  // page renders without the widget

What you see now: the same slowdown, the storefront stays up.

timeline after the fixruns offline
12:00:00  Recommendations 6,000 ms
12:00:01  calls cut at 300 ms, widget empty    ProductPage p99 stays ~120 ms  ✓
12:00:20  breaker OPEN, no calls sent          pool 8/200 busy               ✓
12:02:00  storefront and checkout unaffected   ✓

Land it The widget did not take the site down; the absence of a timeout, a bulkhead, and a fallback did, and each of those is a one-line fix that should have existed on day one.

Likely follow-ups
"You added the timeout and the breaker. Next week recommendations got slow again and the storefront still went down. What did you miss?"

Three things to check, in order. First, whether the timeout is on the right client: if the product page calls recommendations through a shared HTTP client bean, and the one I configured is a different bean, my setting did nothing.

I would verify with a thread dump during the slowdown — if threads are still parked in the recommendations call for longer than 300 milliseconds, the timeout is not active.

thread dump countruns offline
# illustrative output
threads in RecommendationsClient.fetch for more than 300 ms:
  before fixing the bean: 142   ✗ timeout not active
  after fixing the bean:    0   ✓

Second, whether the breaker is scoped per dependency: a Resilience4j breaker shared across several clients trips on aggregate failure and does not isolate this one.

Third, whether the fallback itself calls something slow — a fallback that reads a "default recommendations" list from the same struggling cache is not a fallback. And I would recheck the gateway's health check, because if it is still deep, everything else is irrelevant.

The verification for each is a chaos test in staging that slows recommendations and watches the product page's p99 stay flat.

"How do you size the bulkhead at 10% — why not 50%, and what if 10% is not enough for recommendations under normal load?"

The bulkhead is sized from what the call costs under normal conditions, not from what it might need under bad ones. Little's law gives the number: concurrent calls equals request rate times average latency.

If the product page does 200 requests a second and recommendations answers in 40 milliseconds, that is 8 concurrent calls in steady state, so a bulkhead of 20 on a 200-thread pool is 10% and has more than double the headroom.

Fifty percent would let a slow recommendations service take half the product page's capacity, which is exactly the coupling I am removing.

If 10% is genuinely not enough under normal load, the call is more expensive than a "nice to have" should be, and I would look at why — probably it should be cached or made asynchronous.

I verify the number with the bulkhead's rejection metric: near zero in normal operation, rising only when the dependency is slow.

"Where does the dependency classification live, and who enforces it?"

It lives next to the code, as configuration the platform can read, not in a wiki. In the service template each outbound client is declared with a criticality field — critical or degradable — in the same YAML block as its timeout and breaker settings.

A degradable client must have a fallback bean registered, and a startup check fails the application if one is missing, which turns the rule into a compile-time-like guarantee.

The classification is also exported as a metric label so the dependency dashboard shows which calls are allowed to fail.

Enforcement is mostly mechanical: the build check for fallbacks, a contract test that exercises the fallback path with the dependency stubbed to time out, and a quarterly game day that slows one degradable dependency and expects the SLO to hold.

A human reviews the classification only when a new client is added, and the question is one line: if this is down, does the page still render?

"The product owner asks why recommendations was ever synchronous on the page render at all."

Because it was easy and it was fast at the time, which is how most of these end up. The honest answer is that it should have been asynchronous from the start, and there are two clean ways to do that.

The first is client-side: the page renders without the widget and the browser fetches recommendations separately, so the widget's latency never touches the page's time to first byte.

The second is precomputation: a recommendations consumer writes each user's top items into a store the product page reads locally with a tiny timeout, so the render is a key lookup rather than a computation.

Either approach removes the dependency from the critical path entirely, and the timeout and breaker become belt and braces rather than the only thing standing between a widget and an outage.

I would propose the client-side fetch as the quick change and the precomputed store as the durable one.

Q83. "Load shedding versus backpressure — what is the difference, and what does 'prioritised shedding' look like in practice?"

Reveal answer

Strong answer Both stop a queue from growing without bound; they differ in who acts.

Load shedding is the server's decision: when its queue is longer than it can serve within its latency objective, it rejects new requests immediately with a 503 or 429, spending microseconds on each rejection instead of a thread and an eventual timeout.

Backpressure is a signal to the producer: slow down to the pace the consumer can sustain.

Kafka gives backpressure structurally — a slow consumer simply falls behind and the broker's disk holds the backlog; reactive streams give it in-process through demand signalling; plain HTTP gives none, which is why HTTP servers must shed.

Prioritised shedding means the server rejects the least valuable work first.

In practice, requests carry a priority, derived from one of three things:

  • The endpoint: checkout above browse.
  • The caller: logged-in above anonymous.
  • A header: set by the gateway.

The server keeps separate admission limits per priority, so under overload it serves all checkouts and rejects half the browses.

There are two ways to build it. The simplest is a bounded queue per priority class in front of the worker pool.

The more sophisticated is an adaptive concurrency limit that measures latency and shrinks the admitted concurrency when it rises, then applies the shrinkage from the lowest priority upward.

Either way the rejection must be cheap and must not be retried immediately by the client — a Retry-After header says so.

Picture it A checkout service under a traffic spike with one bounded queue per priority: occupancy at three moments, and the 503 a shed browse request receives. See Pattern: Load shedding.

Make the invisible visible: queue length versus its limit, per priority class, with the shed count.

queue occupancy over timeruns offline
# illustrative output
moment      checkout (limit 40)   browse (limit 20)    shed per second
normal            3/40                 5/20                  0
spike +10 s      22/40                20/20                120 browse   ✓ checkouts still served
spike +60 s      38/40                20/20                480 browse, 15 checkout   (still in the safe zone)

The setup: a semaphore per class in front of the worker pool; a full class is rejected at once.

priority admissionruns offline
Semaphore checkout = new Semaphore(40), browse = new Semaphore(20);
boolean admit(Priority p) {
  return (p == Priority.CHECKOUT ? checkout : browse).tryAcquire();   // never blocks
}
// ❌ TRAP: no Retry-After, clients retry instantly and add load
// ✅ FIX: respond 503 with Retry-After: 2 and release the permit when the request ends

What you see: the cheap rejection the client receives.

HTTP exchangeruns offline
GET /products?page=3  x-request-priority: 3
HTTP/1.1 503 Service Unavailable
Retry-After: 2
(rejected in microseconds, no thread parked)

Land it Shedding is the server protecting itself, backpressure is the producer being told to wait, and priority is what makes shedding lose the work you can afford to lose.

Likely follow-ups
"How does an adaptive concurrency limiter actually decide the limit? Name an algorithm."

The one I have used is the gradient algorithm from Netflix's concurrency-limits library. It keeps a running estimate of the no-load latency — the shortest round trip it has seen recently — and compares it with the current sampled latency. The ratio is the gradient.

When the gradient is near one, latency is not rising with load, and the limit grows by a small step. When latency rises, the gradient falls below one and the limit is multiplied by it, so a 20% latency increase shrinks the limit by roughly 20%.

gradient stepruns offline
no-load latency 100 ms, sampled 120 ms  -> gradient 100/120 = 0.83 -> limit 100 x 0.83 = 83
sampled 100 ms                          -> gradient 1.0           -> limit grows by a small step

It converges on the concurrency at which queueing begins, which by Little's law is the throughput times the no-load latency. The alternative is Vegas-style, borrowed from TCP, which estimates queue length as the difference between expected and actual throughput.

Either way the limiter sits as a filter in front of the worker pool and rejects with a 503 when in-flight requests exceed the limit. The advantage over a fixed limit is that it tracks the capacity of the moment.

"Where do you put the priority — in the request, or derived at the server?"

Derived at the edge and carried in a header, then trusted inside.

The gateway is the only component that knows the whole request context — which endpoint, which user, whether a cart token is present — so it stamps a header such as x-request-priority: 0 through 3 and strips any value a client sent.

Services inside the cluster read the header and use it for their own queues, and they propagate it on outbound calls so that a low-priority browse stays low-priority all the way down to the database layer.

This matters because a priority that is decided independently per service becomes inconsistent, and a browse request that is shed at the product service but admitted at pricing has wasted the pricing work.

The risk is a client forging the header, which is why the gateway overwrites it, and the mesh's authorisation policy can enforce that only the gateway's identity may set it.

"Kafka gives backpressure for free, you said. What is the failure mode of that free backpressure?"

The backlog is invisible to the producer and to the customer. The producer keeps writing at full speed because the broker's disk accepts everything, and nothing tells the upstream that the consumer is an hour behind.

The failure shows up as staleness rather than errors: a customer's order sits in a topic for an hour and nobody is paged, because no request failed.

That is why consumer lag has to be an alert in its own right, with a threshold expressed in time — say, the oldest unprocessed message is older than two minutes — rather than in message count, which means nothing without the rate.

The second failure mode is retention: if the consumer is behind for longer than the topic retains, messages are deleted before they are read, and that is data loss with no error anywhere.

So free backpressure still needs a lag alert, retention sized against the longest plausible outage, and a plan for how the consumer catches up faster than it fell behind.

"What does the client do with a 503 and a Retry-After, and what if it ignores it?"

A well-behaved client reads the Retry-After value in seconds, waits at least that long with added jitter, and retries once. A browser front end shows "we are busy, retrying shortly" rather than an error.

Internal clients built from the service template do this automatically because the retry policy treats 503 with Retry-After as a wait instruction, not as an immediate retry.

If a client ignores the header and retries instantly, the shedding still works on the server side — each rejection costs microseconds — but the client is now generating load that gets it rejected faster.

For that case the gateway's rate limiter is the second line: a client that exceeds its per-key limit gets a 429 with a longer wait, and a partner that keeps hammering gets its key throttled harder.

I also log the client identity on shed requests so the misbehaving client can be found and, if it is a partner, talked to.

Q84 · Scenario. "The catalogue database's CPU spikes to 100% for two seconds exactly every five minutes, and a few hundred product-page requests fail each time. Diagnose and fix."

Reveal answer

Strong answer A spike with a fixed period is a synchronised event, and the period is almost certainly a cache time-to-live.

Evidence: the cache configuration for catalogue data (a five-minute TTL with no jitter), the database's query log at the spike (hundreds of identical queries in the same second), and the number of product-page instances.

The mechanism is a thundering herd: every instance's cache entry for the same hot keys expires at the same moment, every request in flight misses, and all of them go to the database at once.

Causes ranked: a fixed TTL set at startup so all instances expire together; no request coalescing, so a hundred concurrent misses become a hundred queries; and a restart that aligned every instance's clock.

Fixes:

  1. Jitter: add it to the TTL — 300 seconds plus a random 0 to 60 — so keys expire spread out.
  2. Single-flight loading: only one request per key fetches while the others wait for its result. Caffeine's get(key, loader) does this per instance; a short Redis lock does it across instances.
  3. Stale-while-revalidate: switch hot keys to refresh in the background before expiry, so no request ever waits on a miss.

Prevention: a rule that every cache TTL has jitter, and a load test that includes a cold-cache start.

Picture it Hundreds of product-page requests hitting the catalogue database in the same second every five minutes, and the same moment after jitter and single-flight. See Pattern: Cache-aside.

Make the invisible visible: forty instances, all with the entry written at start-up, all expiring together.

database queries per second at 12:05:00runs offline
# illustrative output
second     identical "SELECT ... FROM product WHERE id=?" queries   CPU
12:04:59                   6                                          9%
12:05:00                 320   (40 instances x 8 concurrent misses)   100%  ✗
12:05:01                   6                                          9%

The setup: a fixed 300-second TTL and a plain get-then-load on a miss.

cache setupruns offline
Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(300)).build();   // ❌ TRAP: same expiry everywhere
Product p = cache.getIfPresent(id);
if (p == null) { p = repo.load(id); cache.put(id, p); }                   // ❌ TRAP: every miss loads

The fix: a jittered expiry and one load per key.

jitter and single-flightruns offline
LoadingCache<Long, Product> cache = Caffeine.newBuilder()
    .expireAfter(new Expiry<Long, Product>() {            // ✅ FIX: 300 s + 0..60 s
      public long expireAfterCreate(Long k, Product v, long now) {
        return TimeUnit.SECONDS.toNanos(300 + ThreadLocalRandom.current().nextInt(61)); }
      public long expireAfterUpdate(Long k, Product v, long now, long d) { return d; }
      public long expireAfterRead(Long k, Product v, long now, long d) { return d; }
    }).build(repo::load);                                  // ✅ FIX: one load per key

What you see now: the same query counter, spread out and coalesced.

database queries per second after the fixruns offline
# illustrative output
12:05:00     8
12:05:20     6
12:05:41     9        max over the window: 9 queries/s, CPU ~10%  ✓

Land it A periodic spike is a synchronised expiry, and jitter plus single-flight loading turns the herd into a trickle.

Likely follow-ups
"You added jitter and the spikes are still there, just smeared across ten seconds. What next?"

Then jitter has done its job of spreading the herd, and what remains is the herd itself being too big. That points at the second half of the fix not being in place: single-flight loading.

If a hundred requests miss on the same key in the same second, they all go to the database even with jitter, because jitter only spreads keys, not requests for one key.

I would check the cache's loading path: Caffeine's get(key, mappingFunction) coalesces per instance, but a plain getIfPresent followed by a load on miss does not.

Across instances I would add stale-while-revalidate so the value is refreshed in the background before expiry and no request ever waits on a miss.

If it is still there, I check whether the query itself is expensive enough that even a trickle hurts — a product query with five joins at 100 milliseconds is a different problem from a cache pattern, and the fix is a precomputed row or an index.

The verification is the database's query log: identical queries per second at the old spike time should drop to single digits.

"Show me the Caffeine configuration for jitter and background refresh."

Caffeine does not have a jitter option, so the jitter comes from a custom Expiry. The builder looks like Caffeine.newBuilder().maximumSize(50_000).expireAfter(new Expiry<K,V>() { ... }) where expireAfterCreate returns 300 seconds plus a ThreadLocalRandom value up to 60 seconds, converted to nanoseconds.

Background refresh is refreshAfterWrite(Duration.ofMinutes(4)), which is shorter than the expiry, so when a key is read after four minutes Caffeine returns the current value immediately and reloads it asynchronously using the CacheLoader's asyncReload on the configured executor.

That gives stale-while-revalidate on hot keys, since only a key that is being read gets refreshed. Cold keys simply expire. Single-flight is inherent: Caffeine's LoadingCache.get ensures one load per key at a time and other callers wait for it.

I set the executor explicitly so refreshes do not share the request thread pool.

"What if the spike is not a cache — how would you rule that out?"

By looking at what the database was doing at the spike, not at the application. pg_stat_statements or the slow query log at 12:00:00 and 12:05:00 shows either hundreds of identical product-by-id queries — a cache herd — or a single expensive statement — something else.

pg_stat_statements at 12:05:00runs offline
# illustrative output
calls=320  mean_exec_time=4ms     SELECT ... FROM product WHERE id = $1     -> cache herd
calls=1    mean_exec_time=1900ms  REFRESH MATERIALIZED VIEW ...             -> not a cache

The "something else" candidates with a five-minute period are a scheduled job in the service, a metrics scrape that runs a heavy query, a Kubernetes CronJob, a materialised view refresh, or autovacuum on a table with a five-minute threshold, though vacuum is rarely that regular.

I would also check whether the period lines up with a specific pod's restart or a health check interval.

A quick discriminator is whether the spike is still there when I disable the cache in staging: if it vanishes, it was the herd; if it is unchanged, it was never the cache.

"The request coalescing across instances uses a Redis lock. What happens when Redis is slow?"

Then the lock becomes the bottleneck, and the design must fail open.

The cross-instance single-flight works by one instance acquiring a short-lived key with SET key value NX PX 2000, loading from the database, writing the value to Redis, and releasing; the other instances see the lock, wait briefly, and read the value.

If Redis is slow, every miss now waits on a slow lock call, and the latency of the miss path climbs. The rule I apply is that the lock call has a 5-millisecond timeout and a failure is treated as "no lock available, load locally".

That means during a Redis slowdown the herd protection across instances is lost and each instance loads once per key, which is the per-instance coalescing that Caffeine still provides. That is a degraded but bounded state.

I would rather take a hundred queries per key per expiry across a hundred instances than make the product page wait on a lock server.

Q85 · Design. "Design the caching for the product catalogue: 2 million products, 50,000 reads a second, prices change a few times a day, descriptions rarely. Where does each layer go and what is its TTL?"

Reveal answer

Strong answer Requirements: reads must not touch the catalogue database at anything near 50,000 a second; a stale price is acceptable for browsing but not for checkout; a stale description is fine for an hour. Design in layers, outside in.

A CDN caches the rendered product page and images for anonymous users with a 60-second TTL and a surrogate-key purge on product change, absorbing most of the anonymous traffic.

In the product service, a local cache (Caffeine) holds the hottest 50,000 products by id, 5-minute TTL with jitter, single-flight loading, and stale-while-revalidate, because it costs no network hop.

Behind it a shared cache (Redis or Valkey) holds all 2 million as serialised records, 1-hour TTL, so a new instance warms from Redis rather than from the database and all instances converge on the same value.

Prices are invalidated actively. The pricing service publishes PriceChanged, a consumer deletes the Redis key, and it publishes a small invalidation message that each instance's local cache listens to.

Checkout does not read any of this; it calls pricing synchronously for the final amount.

Trade-offs: three layers to reason about and a bounded window of staleness. What I would not do is put a database read replica in as the "cache", because it does not remove the query load, only moves it.

Picture it Where 50,000 reads a second go after each layer, and what happens when one instance misses a price invalidation. See Pattern: Cache-aside.

Make the invisible visible: the request rate left after each layer, using the numbers from the first follow-up.

read path with ratesruns offline
50,000 reads/s
  CDN (60% anonymous, 60 s TTL)   absorbs 30,000   -> 20,000 reach the product service
  Caffeine local (80% hit)        absorbs 16,000   ->  4,000 reach Redis
  Redis (all 2 M products)        absorbs ~3,950   ->    <100 reach the database
  Checkout bypasses all of it: ~80 prices/s straight to pricing (primary-key lookup)

The trace: a price change and the instance that missed the message.

price change timelineruns offline
12:00:00  pricing publishes PriceChanged(sku-9, 19.90 -> 17.90)
12:00:01  consumer DEL redis:sku-9 and PUBLISH invalidate sku-9
12:00:01  instance A: invalidate(sku-9)   ✓ next read loads 17.90
12:00:01  instance B (disconnected)       ✗ never hears it, serves 19.90
12:05:00  instance B local TTL expires    ✓ loads 17.90 (stale for at most 5 minutes)
checkout at 12:00:30: asks pricing -> 17.90 ✓ (never reads the local cache)

Land it Local for speed, shared for convergence, CDN for volume, and active invalidation for the one field that must not lie — with checkout bypassing all of it.

Likely follow-ups
"How does the local-cache invalidation message reach every instance, and what happens if one instance misses it?"

The invalidation travels on a small Kafka topic or a Redis pub/sub channel that every product-service instance subscribes to at startup.

When the price consumer deletes the Redis key it also publishes the product id to that channel; each instance's listener calls cache.invalidate(id) on its Caffeine instance.

Redis pub/sub is fire-and-forget — a message published while an instance is disconnected is lost — so an instance that missed it serves the stale price until its 5-minute local TTL expires.

That is acceptable for browsing, because checkout never reads the local cache, and it is the reason the local TTL is minutes and not hours. If I needed tighter guarantees I would use a compacted Kafka topic for invalidations, so a reconnecting instance replays recent ones.

I measure it with a metric: the age of the last invalidation received per instance, and an alert if any instance has not heard one while others have.

"Where does the 50,000 reads a second actually land after your layers? Give me the numbers."

Roughly: if 60% of traffic is anonymous page views, the CDN takes 30,000 a second.

With a 60-second TTL on 2 million pages, only pages that are both requested and expired reach the origin. For a typical catalogue with a steep popularity curve that is a few hundred a second.

The remaining 20,000 hit the product service. The local Caffeine cache of the hottest 50,000 products serves perhaps 80% of those, so 4,000 a second go to Redis.

Redis serves nearly all of them, because it holds every product; the misses are new products and expired entries, a few dozen a second. The database therefore sees under 100 reads a second in steady state and a burst after a Redis flush.

Checkout adds its synchronous pricing calls, which at 500 orders a minute is negligible. The number I watch is the Redis hit rate: if it drops below 99%, either the TTL is too short or the working set moved.

"The requirement changes: prices are now personalised per customer segment. Does the design survive?"

The description and image layers survive untouched; the price layer changes. A personalised price cannot be a field on the shared product record, because the same product now has many prices. Two options.

If there are a handful of segments — say ten — the Redis record holds a price per segment, the invalidation deletes the whole key, and the CDN varies its cache key on a segment cookie, which multiplies CDN storage by ten but keeps everything else.

If prices are truly per customer, they do not belong in the catalogue cache at all: the page renders with the base price and the browser fetches the personalised price from the pricing service through a separate small endpoint with its own short-TTL cache keyed by customer and product.

The CDN then caches the product page once for everyone. That second design is what I would push for, because per-customer data in a shared cache is both a cache-efficiency problem and a data-leak risk.

cache keys per designruns offline
today:         product:sku-9            -> price 19.90
segments:      product:sku-9:seg-gold   -> price 17.90   (CDN varies on a segment cookie)
per customer:  GET /price?sku=sku-9&customer=c-7 -> 16.90  (own short-TTL cache, page cached once)
"Why is checkout bypassing the cache not a scalability problem in itself?"

Because checkout is a tiny fraction of the reads and it asks for a handful of products, not a page.

At 500 orders a minute with ten items each, the synchronous pricing call is about 80 product prices a second, which the pricing service answers from its own database with a primary-key lookup in a millisecond. Compare that with 50,000 browse reads a second.

The bypass also buys the one guarantee that matters: the customer is charged the price that is current at the moment of purchase, and the order stores that price, so a later price change does not alter what they paid.

If checkout volume grew a hundredfold, I would let pricing serve from its own local cache with a very short TTL and active invalidation, still not from the catalogue's browsing cache.

What I would never do is quote a price from a 60-second CDN cache at the moment of charging.

"What would you cut under time pressure?"

I would cut the active invalidation and the local Caffeine layer, and ship the CDN plus Redis with plain TTLs.

Redis at a 5-minute TTL for prices and an hour for descriptions absorbs almost all the load on its own, and the CDN takes the anonymous majority.

The cost is that a price change takes up to five minutes to show on browsing pages, which I would confirm with the business is acceptable for a first release.

Checkout still calls pricing directly, so nobody is charged a stale price — that part I do not cut. The local cache and the invalidation topic come in the second iteration, driven by Redis latency or cost rather than by speculation.

What I would not skip even under pressure is jitter on the TTLs and single-flight loading on the Redis miss path, because those are two lines of configuration and their absence is the thundering-herd incident from the previous question.

Q86 · Scenario. "Kubernetes marked every pod of the checkout service unready within thirty seconds, and the service disappeared entirely. Checkout's own code was fine. What happened?"

Reveal answer

Strong answer Every pod failing readiness at once, with healthy code, means the readiness check depends on something all pods share — a dependency.

Evidence: the readiness endpoint's definition (does it call payment or the database?), the dependency's status at the time, and the readiness probe's failure threshold and period.

The mechanism, in order:

  1. The readiness check was deep: it pinged a downstream.
  2. The downstream was slow, so every probe timed out.
  3. After the failure threshold Kubernetes removed all endpoints from the Service.

The platform amputated a service that could have served degraded responses or at least queued.

Causes ranked: a deep readiness check; a probe timeout shorter than the dependency's degraded latency; and no distinction between liveness and readiness, so pods may also have been restarted, which made it worse.

The fix: readiness tests only what the instance needs to serve — is the process up, is its own connection pool initialised, has it warmed its caches — and never a downstream call; dependency health belongs inside circuit breakers where a slow dependency yields a fallback rather than a removed instance.

Spring Boot's /actuator/health/readiness excludes downstream HTTP checks by default for this reason, and I would keep it that way. Prevention: a platform rule that readiness and liveness endpoints are reviewed like any other API, with a specific prohibition on remote calls.

Picture it Checkout pods whose readiness probe calls the payment service, probe by probe, until the Service has no endpoints. See Pattern: Health checks.

The setup: a deep readiness endpoint and the probe settings that judge it.

probe settingsruns offline
readinessProbe:
  httpGet: { path: /actuator/health/readiness, port: 8080 }
  periodSeconds: 10
  timeoutSeconds: 1
  failureThreshold: 3        # 3 failures in a row = removed from the Service
# ❌ TRAP: the readiness group includes a check that calls payment (2 s when degraded)

The trace: every pod runs the same check against the same slow dependency.

probe timelineruns offline
t=0 s    payment slow (2,000 ms)
t=10 s   pod-1..4 probe: deep check waits 2 s, probe timeout 1 s   ✗ failure 1/3
t=20 s   all pods                                                   ✗ failure 2/3
t=30 s   all pods                                                   ✗ failure 3/3 -> NotReady
         Service endpoints: 4 -> 0   (checkout code was healthy the whole time)

What you see: the events and the empty endpoint list.

kubectl outputruns offline
# illustrative output
$ kubectl describe pod checkout-7d9f-abc12 | grep -i readiness
  Warning  Unhealthy  Readiness probe failed: Get "http://10.1.2.3:8080/actuator/health/readiness": context deadline exceeded
$ kubectl get endpoints checkout
NAME       ENDPOINTS   AGE
checkout   <none>      41d

The fix: readiness checks only the instance itself; payment slowness is handled by a circuit breaker and fallback.

application.ymlruns offline
management:
  endpoint:
    health:
      group:
        readiness:
          include: readinessState          # ✅ FIX: local state only, no downstream call

What you see now: same slowdown, pods stay ready.

kubectl output after the fixruns offline
# illustrative output
$ kubectl get endpoints checkout
NAME       ENDPOINTS                                      AGE
checkout   10.1.2.3:8080,10.1.2.4:8080,10.1.2.5:8080 +1  41d   ✓ payment slow, requests degrade, pods stay

Land it A health check that reports on dependencies turns a partial failure into a total one, so readiness answers only "can I take a request", never "will it succeed".

Likely follow-ups
"What is the difference between liveness, readiness, and startup probes, and what should each one check?"

They answer three different questions and have three different consequences. Liveness asks "is this process alive or wedged?" — if it fails, Kubernetes restarts the container.

It should check only that the process can respond: a trivial endpoint with no dependencies, because a restart does nothing for a slow database. Readiness asks "can this instance take traffic right now?" — if it fails, the pod is removed from the Service endpoints but not restarted. It checks the instance's own state: the connection pool is initialised, caches are warmed, and the application has not been told to shut down.

A startup probe asks "has the application finished starting?" and suspends the other two probes until it passes, with a generous failure threshold, so a JVM that takes ninety seconds to start is not killed by an impatient liveness check.

In Spring Boot these map to /actuator/health/liveness and /actuator/health/readiness, with the startup probe pointing at readiness with a long failureThreshold.

three probesruns offline
startupProbe:   { httpGet: { path: /actuator/health/readiness, port: 8080 }, periodSeconds: 3, failureThreshold: 30 }  # up to 90 s to start
livenessProbe:  { httpGet: { path: /actuator/health/liveness,  port: 8080 }, periodSeconds: 10 }   # restart if wedged
readinessProbe: { httpGet: { path: /actuator/health/readiness, port: 8080 }, periodSeconds: 10 }   # remove from Service
"Isn't there a case for a deep check? What if the database really is down for this one pod?"

There is, and the distinction is whether the failure is local to the pod or shared. A pod whose own connection pool cannot reach the database because its node has a broken network path is a local failure, and pulling that pod is correct.

A database that is down for every pod is a shared failure, and pulling every pod is what turned a degraded service into a vanished one.

The way to have the first without the second is to check the pool's state, not the database: Spring Boot's DataSourceHealthIndicator runs a validation query, which is the deep check I exclude from readiness; instead I check HikariPoolMXBean.getActiveConnections() and whether the pool has any connection at all, which reflects local reachability without probing the server on every check.

And I make the effect asymmetric: readiness fails only if the local check fails for longer than a threshold, and the platform enforces a minimum available fraction through a PodDisruptionBudget, which does not stop readiness removal but does make the scale of the problem visible.

"How would you verify in production that no readiness check calls a downstream?"

Two ways, one static and one dynamic.

Statically, the service template owns the health configuration, and a build-time test asserts that the readiness health group contains only the indicators the platform allows — readinessState and the local pool indicator — by reading management.endpoint.health.group.readiness.include and failing on anything else.

Dynamically, the tracing data proves it: every readiness probe is an HTTP request, and if it is traced, a span for a readiness call that has a child span to another service is a violation.

I would run a query in the trace backend for spans named with the readiness path that have children with a peer service attribute, and page the owning team on any hit.

The cheaper variant is a mesh-level policy that denies outbound calls originating from the health endpoint, but that is harder to express. The trace query is a one-off audit I would run quarterly.

"The fix didn't work — you made readiness shallow and pods still disappeared during a dependency slowdown. Why?"

The most likely reason is that the probe timed out for a different cause: the readiness endpoint shares the request thread pool with real traffic.

When the dependency was slow, every worker thread was parked waiting on it, and the readiness request sat in the accept queue past the probe's one-second timeout, which counts as a failure. The endpoint was shallow, but it could not get a thread.

The fix is to serve the actuator on a separate port with its own small thread pool — management.server.port=8081 in Spring Boot — so the health check is answered even when the main pool is exhausted, and, separately, to fix the missing timeout that let the pool exhaust in the first place.

application.ymlruns offline
management:
  server:
    port: 8081        # ✅ FIX: probes answered by their own small pool, even when the main pool is full

The second candidate is a liveness probe that was still deep, restarting pods, which looks the same from outside. I would confirm from the pod events: "Readiness probe failed: context deadline exceeded" versus "Liveness probe failed".

Q87 · Scenario. "Every deploy causes a burst of 502s for about ten seconds and a handful of half-processed Kafka messages. The deploy is a standard rolling update. Why, and what does a clean shutdown require?"

Reveal answer

Strong answer The symptom is pods being killed while they still hold work.

Evidence: the pod's termination sequence (is there a preStop hook, what is terminationGracePeriodSeconds), whether the application handles SIGTERM, and whether the load balancer keeps routing to a pod after it was told to stop. The mechanism has two races.

First, when Kubernetes decides to stop a pod it removes it from the Service endpoints and sends SIGTERM at roughly the same time, and the endpoint removal takes a few seconds to propagate to every proxy, so requests keep arriving at a pod that has begun shutting down; without a pause, those get 502s.

Second, if the application exits on SIGTERM without finishing in-flight requests and Kafka batches, work is lost or redelivered.

A clean shutdown requires, in order:

  1. A preStop sleep of 5 to 10 seconds, so endpoint removal propagates before the process is signalled.
  2. A drain on SIGTERM: the application stops accepting new requests, finishes in-flight ones, stops the Kafka consumer and commits offsets, closes the pool, and exits. Spring Boot does this with server.shutdown=graceful and spring.lifecycle.timeout-per-shutdown-phase.
  3. A grace period longer than the sum of those.

Prevention: the service template ships with these settings, and a deploy in staging is watched for error spikes as a gate.

Picture it The first fifteen seconds of a pod's termination, with and without a preStop sleep, counting the requests that still arrive.

The trace: endpoint removal and SIGTERM start together; the proxies learn about it a few seconds later.

termination timeline without preStopruns offline
t=0 s    pod marked Terminating; endpoint removal starts; SIGTERM sent at once
t=0.1 s  app stops accepting connections
t=1 s    proxies still route 40 req/s to this pod      ✗ connection refused -> 502
t=5 s    last proxy learns the endpoint is gone
         ~160 requests failed, plus Kafka batch killed mid-poll   ✗

What you see: the 502 burst in the gateway log.

gateway access logruns offline
# illustrative output
12:10:01 GET /orders/o-91  upstream=10.1.2.3:8080  502  0ms
12:10:02 GET /orders/o-93  upstream=10.1.2.3:8080  502  0ms
(about ten seconds of these per rolling deploy)

The fix: sleep first, then drain, using the settings in the first follow-up.

termination timeline with preStopruns offline
t=0 s    pod Terminating; endpoint removal starts; preStop sleep 8 begins
t=0-5 s  proxies catch up, pod still answers normally    ✓ no 502
t=8 s    SIGTERM; graceful shutdown drains in-flight work, commits offsets  ✓
t=12 s   process exits (grace period 45 s was never reached)

What you see now: the same access log across a deploy.

gateway access log after the fixruns offline
# illustrative output
12:10:01 GET /orders/o-91  upstream=10.1.2.3:8080  200  38ms
12:10:09 GET /orders/o-95  upstream=10.1.2.7:8080  200  41ms   ✓ no 502 during the rollout

Land it A rolling deploy is only zero-downtime if the pod stops receiving traffic before it starts shutting down and finishes its work before it exits, and both of those are settings someone has to write.

Likely follow-ups
"Walk me through the exact Kubernetes and Spring settings and the order they fire in."

The pod spec has a preStop sleep and a grace period, and Spring has graceful shutdown with a phase timeout.

pod specruns offline
terminationGracePeriodSeconds: 45
containers:
- name: order
  lifecycle:
    preStop: { exec: { command: ["sleep", "8"] } }
application.ymlruns offline
server:
  shutdown: graceful
spring:
  lifecycle:
    timeout-per-shutdown-phase: 30s

The sequence when a pod is deleted: Kubernetes marks the pod terminating and, in parallel, starts removing it from the Endpoints and runs the preStop hook.

The preStop sleep gives the endpoint removal about eight seconds to reach every kube-proxy and mesh sidecar, during which the pod still answers requests normally.

When the hook finishes, the kubelet sends SIGTERM. Spring's graceful shutdown then stops accepting new connections, waits up to thirty seconds for in-flight requests to finish, stops the Kafka listener containers so they commit their offsets and leave the group, closes the connection pool, and exits.

The grace period of 45 seconds covers 8 plus 30 with margin; if the process is still running when it expires, the kubelet sends SIGKILL.

"What does the Kafka consumer specifically need to do on shutdown, and what goes wrong if it does not?"

It needs to stop polling, finish the records it has already taken, commit the offsets for exactly those records, and then call close(), which sends a LeaveGroup to the coordinator.

If it is killed mid-batch without committing, the next owner of the partition resumes from the last committed offset, and every record after that is redelivered — the half-processed messages from the question.

If it exits without leaving the group, the coordinator waits for the session timeout, 45 seconds by default, before it notices, and the partition sits unconsumed for that long.

Spring Kafka handles both when the container is stopped normally: it finishes the current poll's records, commits, and leaves.

What I set explicitly is spring.kafka.listener.immediate-stop=false so it drains the batch rather than abandoning it, and I keep the batch small enough that draining fits inside the shutdown timeout. And the handler is idempotent anyway, because a SIGKILL after the grace period can still happen.

"Why does a preStop sleep work at all — isn't it a hack?"

It is a workaround for a real gap in the design: Kubernetes does not wait for endpoint removal to propagate before signalling the process, because there is no acknowledgement path from every proxy back to the kubelet.

The sleep buys time for an eventually consistent system to converge. It is not elegant, but it is the accepted practice, and it costs eight seconds per pod per deploy. The cleaner improvements are partial.

Since Kubernetes 1.26 the EndpointSlice terminating condition lets proxies stop sending new connections to a terminating pod faster, and a mesh like Istio drains connections on SIGTERM itself.

The application can also start failing its readiness probe on SIGTERM, which Spring Boot does automatically, so the removal is signalled from both ends.

Even with all of that, I keep a short sleep, because the cost of being wrong is a burst of 502s and the cost of being conservative is a few seconds of deploy time.

"After all that, the 502s dropped but did not disappear. Where are the rest coming from?"

From the other end of the rollout: the new pod taking traffic before it is ready.

If the readiness probe passes as soon as the HTTP port opens but the JVM is still warming — classes loading, connection pool filling, caches cold — the first requests to the new pod are slow or fail, and a gateway with a short timeout reports 502.

I would look at the new pod's first thirty seconds of latency compared with steady state.

The fixes are a readiness check that waits for the pool to be initialised and a warm-up step that runs a few representative requests internally before reporting ready; a startup probe with a longer threshold makes that safe.

The other candidate is the load balancer in front of the ingress, which has its own health check interval and can send traffic to a node whose pod is gone for a few seconds; setting externalTrafficPolicy and the load balancer's health check to the ingress's readiness closes that.

I confirm by matching each 502's timestamp to a pod's start or stop event.

Q88 · Design. "Design load shedding for the checkout service so that under a 5× traffic spike, paying customers finish and the service never falls over."

Reveal answer

Strong answer Requirements: survive 5× normal load; serve every request that is mid-checkout before any that is starting; degrade visibly rather than fail invisibly. Design from the edge inward.

At the gateway, a rate limit per client and a global admission limit set at roughly 1.5× the service's tested capacity, returning 429 with Retry-After beyond it; this stops the excess from ever reaching the service.

At the gateway too, requests are tagged with a priority: "in-progress checkout" (has a cart token and a payment step) above "start checkout" above "estimate shipping".

In the service, a bounded queue per priority in front of the worker pool — sizes chosen so the total queue never holds more work than the service can finish within its latency objective — and a fast 503 for the class whose queue is full, lowest class first.

An adaptive concurrency limiter measures p99 latency and shrinks the admitted concurrency when it rises, so the limits track the real capacity of the moment rather than a number from last quarter's load test.

Downstream, bulkheads on payment and inventory so a slow one cannot consume the pool.

A queue-based fallback for "start checkout": when shed, the client is told to wait and retry with jitter, which spreads the spike over time.

Trade-offs: priority tagging needs the gateway to understand the flow. What I would not do is scale out as the only answer; autoscaling takes minutes and a spike takes seconds.

Picture it A 5x spike in requests per second, class by class, through the gateway limit and the in-service queues. See Rate limiting and Load shedding.

Make the invisible visible: the actors and their limits, with worked numbers: normal load 400 req/s, tested capacity 800 req/s, gateway admission limit 1.5 x 800 = 1,200 req/s.

admission arithmeticruns offline
# illustrative output
spike = 5 x 400 = 2,000 req/s   mix: in-progress 400, start 600, estimate 1,000
class               arrives   gateway (limit 1,200)   service (capacity 800)
in-progress (p0)       400        400 admitted            400 served        ✓
start checkout (p2)    600        600 admitted            400 served, 200 -> 503 + Retry-After
estimate shipping (p3) 1,000      200 admitted            0 served, 200 -> 503; 800 -> 429 at the gateway
total served: 800 = what the service can finish, never more

The trace: one customer at the payment step during the spike.

request pathruns offline
POST /checkout/c-77/payment  cart-token valid
  gateway: signed token verified locally -> priority 0   ✓
  admission: 1,200 limit not reached for p0              ✓
  service: p0 queue 12/40, served in 140 ms              ✓ customer pays

Land it Admit at the edge, prioritise by how close the customer is to paying, and let a latency-driven limiter set the number, because capacity is whatever the system can do right now.

Likely follow-ups
"Where does the 1.5× admission number come from, and how do you keep it honest?"

It comes from a load test, and it is only as good as the last time the test ran.

I run the checkout service in a staging environment with production-shaped data and ramp traffic until p99 latency crosses the SLO threshold; that request rate is the tested capacity.

The gateway's admission limit is set at 1.5 times it, which sounds like it admits too much, but the point of the gateway limit is to stop the flood, not to be precise — the adaptive limiter inside the service is the precise control.

Keeping the number honest means rerunning the test on every release that touches the checkout path, in the pipeline, and comparing the result with the configured limit; if capacity drops more than 10% the build warns.

I also record the actual capacity observed during real spikes, which the limiter's metrics give me for free, and reconcile the two quarterly. A capacity number nobody has measured in six months is fiction.

"How does the gateway know a request is an in-progress checkout rather than a new one?"

From the shape of the request, without calling anyone. A checkout flow issues a cart token when the customer starts, and each subsequent step — address, payment, confirm — carries it.

The gateway's routing rule reads the path and the presence of that token: POST /checkout/start with no token is priority 2, POST /checkout/{id}/payment with a valid token is priority 0.

The token is a signed value, so the gateway can validate it locally with a public key and cannot be tricked by a forged one.

If the platform wants finer grading, the token can carry a step claim updated at each stage, so "about to confirm payment" outranks "just entered an address".

What the gateway must not do is look the cart up in a database to decide priority; that puts a database call on every request at the edge, which is a new dependency in exactly the place that is supposed to protect against dependencies.

"5× turned into 20× and the service still fell over. What broke, and what would you change?"

At 20× the gateway itself becomes the question. The admission limit still holds at the service, but the gateway has to accept, inspect, and reject 20 times normal traffic, and if the gateway's own capacity is 10× normal it saturates and everything behind it looks down.

So the first change is that rejection has to move outward: the CDN or the edge load balancer applies a coarse rate limit per client IP and returns a static "busy" page, so most of the flood never reaches the gateway.

capacity at 20xruns offline
20 x 400 = 8,000 req/s arriving; gateway capacity 10 x 400 = 4,000 req/s   ✗ saturates before its limit applies
edge per-IP limit drops ~6,000 req/s with a static page  ->  2,000 reach the gateway   ✓

The second is that the 429 responses themselves cost bandwidth and connection slots; a tiny body and an immediate connection close matter at that scale.

The third is the queue-based fallback: at 20× the "wait and retry with jitter" advice becomes a waiting room with explicit admission tokens, because polite retries from a million clients are still a million requests.

I would verify with a load test that ramps to 20× and watches the gateway's CPU and connection count, not just the service's.

"The requirement changes: fairness now matters — a customer who has been waiting longer should get in first. Does priority shedding handle that?"

No, priority shedding is about which class of work survives, not about order within a class, and a bounded queue served in arrival order gives approximate first-come-first-served only for the requests that made it into the queue.

Fairness across arrivals that were shed is not something a stateless limiter can provide.

The design that gives it is the waiting room: a customer who is shed is issued a queue position stored in a shared store, and the gateway admits positions in order at a controlled rate.

The waiting page polls with its position and is let through when its number comes up. That is a product change as much as a technical one — the customer sees a queue — and it costs a small stateful component at the edge.

I would keep priority shedding for in-progress checkouts, because someone at the payment step should finish regardless of how long a new arrival has waited, and add the waiting room for entry into the flow.

"What would you cut under time pressure?"

The adaptive limiter and the priority queues inside the service, which are the parts that need code and tuning.

I would ship the gateway admission limit at the tested capacity, a per-client rate limit, and a fixed concurrency limit in the service sized from the load test, using Resilience4j's bulkhead in front of the checkout controllers.

That gives me "never falls over" with a static number, and it takes an afternoon.

I would keep the priority tagging at the gateway even in the cut-down version, because a single header rule that lets in-progress checkouts bypass the rate limit is cheap and is most of the customer-facing value.

What I defer is the adaptive part that tracks capacity as it changes; until it exists I rerun the load test before every sale and adjust the static number by hand, which is fine for a few months and not fine forever.

Q89 · Scenario. "A team switched the order service to Java 21 virtual threads for throughput. Latency improved for a week, then during a sale the database started refusing connections and the service fell over harder than before. Explain."

Reveal answer

Strong answer Virtual threads removed the limit that had been protecting the database. Evidence: the connection pool's wait and timeout metrics, the number of concurrent requests in the service before and after the change, and the database's connection count and its max_connections.

The mechanism: with 200 platform threads, at most 200 requests could be in flight, so at most 200 could want a database connection, and a pool of 50 queued the rest in an orderly way.

With virtual threads, tens of thousands of requests can be in flight at once, all of them contending for the same 50 connections; the pool's queue explodes, connection-acquire timeouts fire everywhere, and the service returns errors under a load it previously would have served slowly.

The thread limit was an accidental bulkhead.

Causes ranked:

  1. No explicit concurrency limit replacing the thread-pool limit.
  2. A pool sized for the old concurrency.
  3. Pinning: in older library versions, virtual threads pinned on synchronized blocks in JDBC drivers, which is largely fixed as of Java 24's changes to pinning but still worth checking.

The fix: reintroduce an explicit limit — a semaphore bulkhead around database work sized to the pool, plus load shedding above it — and size the pool by the database's capacity (see Chapter E3's pool arithmetic), not by the service's appetite.

Prevention: any change that raises a service's concurrency is a change to its downstream load, and the load test must include the database at the new concurrency.

Picture it The same 50-connection pool seen with 200 platform threads and with virtual threads, at three moments of a sale. See Pattern: Bulkhead.

Make the invisible visible: how many requests can want a connection at once, with the pool and wait times.

concurrency before and afterruns offline
# illustrative output
                      requests in flight   want a connection   pool (50)       waiting
200 platform threads         200                 <=200          50 busy         <=150 (orderly)
virtual threads, normal    1,500                 1,500          50 busy         1,450
virtual threads, sale     20,000                20,000          50 busy         19,950  ✗

What you see: acquire timeouts everywhere after the default 30 s.

logruns offline
# illustrative output
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.
database: FATAL: sorry, too many clients already     (20 pods x 50 = 1,000 connections vs max_connections)

The fix: an explicit limit sized to the pool, in front of the database work.

semaphore bulkheadruns offline
private final Semaphore db = new Semaphore(60);       // ✅ FIX: pool 50 + small queue
<T> T withDb(Callable<T> work) throws Exception {
  if (!db.tryAcquire(100, TimeUnit.MILLISECONDS))
    throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE);   // shed, with Retry-After
  try { return work.call(); } finally { db.release(); }
}

What you see now: at most ten waiters; the rest are shed quickly.

Hikari wait during the saleruns offline
# illustrative output
pool.Wait p99: 4 ms     503 shed: 18% of requests     timeouts: 0    ✓

Land it Virtual threads make waiting cheap, which means the database now needs a bulkhead that the thread pool used to provide for free.

Likely follow-ups
"Size the semaphore for me. The pool has 50 connections and a query takes 20 milliseconds. What limit and why?"

The semaphore should be about the pool size, with a small allowance for queueing, so around 60. The reasoning: with 50 connections and 20-millisecond queries, the pool can serve 2,500 database operations a second.

Allowing 60 permits means at most 10 requests are waiting for a connection at any moment, which at 20 milliseconds each is a worst-case wait of a few milliseconds — still fast, still bounded.

semaphore arithmeticruns offline
50 connections / 0.020 s per query = 2,500 queries/s, one connection frees every 0.4 ms
60 permits -> at most 10 waiting -> 10 x 0.4 ms = ~4 ms wait   ✓
500 permits -> 450 waiting up to connectionTimeout 30 s       ✗

If I set it much higher, say 500, then 450 requests queue in HikariCP for up to connectionTimeout, which defaults to 30 seconds, and the service is back to the collapse. If I set it lower than the pool, connections sit idle.

The permit acquisition itself has a short timeout — 100 milliseconds — and a failure is a 503 with Retry-After, which is load shedding at the database boundary.

I verify the number by watching HikariCP's pool.Wait timer: with the semaphore right, it stays under a few milliseconds even under a spike.

"Why not just make the connection pool bigger?"

Because the database's capacity does not grow when the pool does. PostgreSQL runs one backend process per connection.

Throughput peaks at a small multiple of the CPU core count. Past that, more connections mean more context switching and lock contention, and every query gets slower.

A pool of 500 against an 8-core database is worse than a pool of 50. The pool also multiplies across instances: 20 pods with 50 connections each is already 1,000 connections, which is why max_connections was being refused.

If more concurrency is genuinely needed, the answer is a connection pooler in front of the database — PgBouncer in transaction mode — so thousands of client connections share a few hundred server ones, plus read replicas for the read load.

But the immediate issue in this incident was not that the pool was too small; it was that nothing limited how many requests could want a connection at once, and no pool size fixes that.

"How would you have caught this before the sale?"

With a load test that included the database at the new concurrency, which is the step the team skipped. Their test almost certainly measured the service's throughput with a stubbed or lightly loaded database and saw the improvement.

The right test drives the service at two or three times the expected sale peak with the real database schema and realistic data, and watches three numbers: HikariCP's wait time and timeout count, the database's active connection count, and the service's error rate.

The moment the wait time climbs past a few milliseconds, the concurrency has outrun the pool.

A second signal was available in production during the good week: the pool's active-connection gauge would have been pinned at the maximum during normal peaks, which is the precursor to a timeout under a bigger peak.

An alert on pool saturation above 80% would have fired days before the sale.

"Does the same problem exist with reactive or with Go goroutines, or is it specific to virtual threads?"

It is the same problem in every model that makes waiting cheap, and it has a general name: removing an accidental limit without adding a deliberate one.

WebFlux has it with its event loop and an unbounded number of pending subscriptions; the next question in this drill is exactly that case.

Go has it with goroutines, where a handler per request can spawn a hundred thousand of them all contending for a database/sql pool, and the standard fix there is SetMaxOpenConns plus a semaphore. Node has it with its single thread and unbounded promise chains.

Virtual threads are just the version that arrives silently in a Java codebase, because the code looks identical and only the executor changed.

The principle I state is that every downstream resource needs an explicit concurrency limit sized to that resource, and the thread pool was never the right place for it — it was just where it happened to be.

Q90 · Design. "Design a chaos engineering programme for this platform that finds the next cascading failure before a customer does, without causing one."

Reveal answer

Strong answer Requirements: each experiment has a hypothesis, a blast radius, and an abort condition; nothing runs in production until it has run in staging; the findings turn into changes.

Design: start with a dependency map and a written hypothesis per edge — "if recommendations returns 5-second latency, the product page serves without the widget and its p99 stays under 400 milliseconds".

The injection tools:

  • Mesh fault injection: Istio can add delay or return errors for a percentage of calls to one service.
  • Pod termination: through a controller such as LitmusChaos or Chaos Mesh.
  • Network partition rules.

Each experiment defines the metrics that must hold (the SLO of the affected user path), a maximum duration, and an automatic abort when an SLO burn rate crosses a threshold.

Sequence: run in staging with synthetic load; then in production at 1% of traffic during business hours with the owning team watching, never at night and never during a sale; then widen.

A game day once a quarter runs the top three hypotheses with the on-call team, treating it as a rehearsal.

Every finding becomes a ticket with a fix — usually a missing timeout, bulkhead, or fallback — and the experiment is rerun after the fix as a regression test. Trade-offs: engineering time and the political cost of deliberately hurting production.

What I would not do is random chaos without hypotheses; that finds nothing in particular and scares everyone.

Picture it One experiment on the running example, from hypothesis to abort check to the result before and after the fix. See Circuit breaker and Timeout.

The setup: the hypothesis is written as a pass/fail statement before anything is injected.

experiment definitionruns offline
hypothesis: "recommendations at 5 s latency -> product page p99 stays under 400 ms"
target: recommendations           traffic: 1%        max_duration: 15m
abort_when: slo_burn_rate{path="checkout"} > 30   # evaluated every 30 s

The trace: what the controller does second by second.

experiment run, before the fixruns offline
# illustrative output
12:00:00  inject delay 5 s on 1% of calls to recommendations
12:00:30  product page p99 = 5,400 ms          ✗ hypothesis fails (no timeout)
12:00:30  burn rate 31 > 30 -> controller deletes the fault rule, effect within seconds
finding: ticket "add 300 ms timeout + fallback", owner product-page team

What you see now: the same experiment rerun as a regression test after the fix.

experiment run, after the fixruns offline
12:00:00  inject delay 5 s on 1% of calls to recommendations
12:05:00  product page p99 = 390 ms, widget empty for 1% of pages   ✓ hypothesis holds

Land it Chaos engineering is hypothesis testing with an abort button, and its output is a list of missing resilience controls, not a list of outages.

Likely follow-ups
"What is your abort condition concretely, and how fast does it act?"

The abort condition is the SLO burn rate of the affected user path, evaluated every 30 seconds during the experiment.

Concretely: if the checkout path's error-plus-slow rate over the last five minutes exceeds what would burn the monthly budget in a day — a burn rate of about 30 — the experiment controller removes the fault injection immediately.

For a mesh-based injection that is deleting the Istio VirtualService fault rule, which takes effect within a second or two; for a pod kill it is stopping further kills, since the killed pods are already restarting.

fault rule the controller deletesruns offline
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata: { name: recommendations-chaos }
spec:
  hosts: [recommendations]
  http:
  - fault: { delay: { percentage: { value: 1.0 }, fixedDelay: 5s } }
    route: [ { destination: { host: recommendations } } ]
# burn rate 30 = a 30-day budget spent in one day

So worst case the fault persists for about six minutes: five minutes of window plus the evaluation interval. I also set a hard duration cap of fifteen minutes on any experiment regardless of metrics, and a manual abort button that any watcher can press.

The controller itself has a dead-man switch: if it loses contact with the metrics backend, it aborts, because an experiment you cannot observe is just an outage.

"How do you convince the business to let you break production on purpose?"

By showing that the alternative is letting production break at a time nobody chose. The argument I make is with the last three incidents: each one was a missing timeout or fallback that an experiment would have found in staging with zero customer impact.

Then I make the blast radius concrete and small: the first production experiment affects 1% of traffic to one non-critical dependency for five minutes at 10 a.m. on a Tuesday with the owning team watching, and the abort is automatic.

I define the maximum harm in customer terms — at most a few hundred requests see a slower page — and compare it with the last outage's harm.

I also start in staging and bring the findings, because a list of five real weaknesses found without touching production is persuasive. And I never call it chaos in the pitch; I call it resilience verification, because the word matters to people who sign things.

"An experiment found a weakness, the team fixed it, and the fix broke something else. How does the programme handle that?"

That is why every experiment becomes a permanent regression test rather than a one-off.

The fix — say, adding a fallback for recommendations — is deployed through the normal canary, and then the original experiment reruns against it in staging as part of the pipeline for the product-page service.

If the fix broke something else, the most common case is that the fallback path has its own dependency, and the experiment that slows that dependency finds it.

So the programme keeps a suite: each hypothesis is a runnable definition checked into the owning team's repository, and the pipeline runs the ones tagged for that service. Over time the suite becomes the resilience contract of the service.

When a fix causes a regression the process is the same as any bug: post-mortem, another hypothesis added, rerun. What I avoid is treating the first pass as the finish line.

"What would you cut under time pressure?"

I would cut the production experiments and the tooling, and keep the hypotheses and the staging runs.

The hypotheses are the valuable part: a written dependency map with "if X is slow, Y should still do Z" for the top twenty edges takes a day and immediately shows which edges have no fallback, before anything is injected.

Then in staging I would use the mesh's fault injection, which is a YAML change and needs no new controller, to test the five edges on the checkout path. That finds the majority of the missing timeouts and bulkheads in a week.

What I defer is the automated abort, the quarterly game day, and the production rollout, because those need a controller and organisational buy-in.

What I would not cut is the rule that every finding becomes a ticket with an owner, because an experiment whose result nobody acts on was just an interesting afternoon.

Drill · Observability

This group tests whether you can follow one request across many processes, alert on what users feel rather than what machines do, and keep the telemetry bill from becoming its own incident.

Q91. "Explain how a trace id gets from the gateway into a log line in the fifth service down the chain, step by step."

Reveal answer

Strong answer At the gateway, the tracing library starts a trace — it generates a 16-byte trace id and a span id for the gateway's own work — and when the gateway calls the next service it writes the W3C traceparent header: version, trace id, parent span id, and flags.

The first service's server-side instrumentation reads that header before the controller runs and creates a child span with the same trace id and the incoming span id as its parent.

It stores the span context in a thread-local (or, with virtual threads and reactive code, a scoped context that Micrometer's context propagation carries across thread hops).

Its logging framework's MDC — the mapped diagnostic context, a per-request key-value map — gets trace_id and span_id copied into it by the tracing integration, so every log line written while that span is active includes them.

When this service calls the next one, its client instrumentation writes a new traceparent with the same trace id and its own span id, and the process repeats.

For a Kafka hop, the producer writes the same values into message headers and the consumer's listener reads them, so the consumer's span links back.

By the fifth service the trace id has crossed four network boundaries unchanged; the log line there carries it because of the MDC, and the trace backend assembles the waterfall from spans that all share it.

In Spring Boot 3.5+ and 4.x all of this is automatic with Micrometer Tracing and the OTLP exporter on the classpath.

Picture it One request's trace id followed from the gateway through five services in the log lines, and the log line where a thread hop dropped it. See Pattern: Distributed tracing.

Make the invisible visible: the header each hop reads and writes, and the MDC keys it fills.

header and MDC per hopruns offline
gateway   creates trace 4bf92f35...4736, span 00f067aa...  writes traceparent: 00-4bf92f35...4736-00f067aa...-01
order     reads it, child span a1b2..., MDC trace_id=4bf9..., span_id=a1b2...
payment   reads order's traceparent (same trace id, parent a1b2...), MDC filled
... fifth service: same trace id, four boundaries crossed

What you see: searching the log backend for one trace id.

log searchruns offline
# illustrative output
$ logs search trace_id=4bf92f3577b34da6a3ce929d0e0e4736
gateway    12:00:00.001 INFO  POST /checkout
order      12:00:00.012 INFO  creating order o-91
payment    12:00:00.040 INFO  authorising 24.50 EUR
inventory  12:00:00.085 INFO  reserving sku-9
shipping   12:00:00.120 INFO  quote requested

The trace: a hop through an executor loses the thread-local MDC.

broken hopruns offline
order      12:00:00.015 INFO  [trace_id=4bf92f35...] submitting audit task
order      12:00:00.031 INFO  [trace_id=        ] audit written   ✗ @Async thread, empty MDC
# ✅ FIX: wrap the executor with context propagation (see the second follow-up); the line then carries the id again

Land it The trace id rides a header between services and the MDC inside each one, and the moment either link is broken the request becomes untraceable from that hop onward.

Likely follow-ups
"What is in the traceparent header exactly, and what is tracestate for?"

The traceparent header is four hex fields separated by dashes:

  • Version: two hex digits, currently 00.
  • Trace id: 32 hex characters, which is 16 bytes.
  • Parent span id: 16 hex characters, 8 bytes.
  • Flags: two hex digits, where the lowest bit is "sampled".
traceparentruns offline
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             ^^ version  ^ trace id (16 bytes)      ^ parent span id  ^^ flags: sampled

The sampled flag is how a head-sampling decision travels, so every downstream service records or skips consistently.

The tracestate header is a companion for vendor-specific data: a comma-separated list of key-value pairs such as a vendor's own sampling weight or a legacy id, which each hop may read and rewrite but must forward. Most platforms never populate it.

The important property of both is that they are defined by the W3C Trace Context standard, so a Java service, a Go service, and a proxy from different vendors all agree on the format, which is what makes a trace survive a heterogeneous platform.

"Where does the MDC break, and how does the trace id survive a thread hop?"

The MDC is a thread-local map, so it breaks the moment work moves to another thread: a CompletableFuture.supplyAsync, an @Async method, a custom ExecutorService, or a Reactor pipeline that switches schedulers. The new thread has an empty MDC and logs without a trace id.

The fix is to propagate the context explicitly at the hop. In Spring Boot 3.x with Micrometer, the context-propagation library provides ContextSnapshot, and wrapping an executor with ContextExecutorService.wrap(executor, ContextSnapshotFactory) captures the tracing and MDC context on submit and restores it on run.

For Reactor, Hooks.enableAutomaticContextPropagation() makes the reactor context carry it. For virtual threads it works per thread the same way, since each virtual thread has its own thread-locals, but a task handed to a shared executor still needs the wrap.

I verify by looking for log lines with an empty trace_id field in the log backend and tracing them back to the executor that produced them.

"What does this cost per request, and where does the overhead actually go?"

With sampling at 100% and OTLP export, the in-process cost is typically a few microseconds per span for creation and attribute setting, and the exporter's batching keeps the network cost off the request thread.

For a request with five spans in a service that is a fraction of a percent of a 50-millisecond request.

Where it becomes noticeable is in three places: attribute volume, if someone attaches request bodies or large headers; span count, if an instrumentation creates a span per JDBC statement or per Kafka record in a batch of a thousand; and the exporter queue's memory when the collector is slow.

The MDC copy is a couple of map puts per request. Header propagation adds about 60 bytes per outbound call.

I measure it directly: run the service under load with tracing off and with it on at 100%, and compare p99 and CPU. On a well-configured service the difference is inside the noise, and if it is not, the attributes are the first thing I look at.

"Kafka: the consumer runs minutes after the producer. Is that the same trace or a different one?"

It should be a different trace with a link back, not a child span.

If the consumer's span is a child of the producer's, the trace waterfall shows a five-minute gap and a checkout that "took" five minutes, which is misleading, and the trace backend may have already closed and indexed the parent.

OpenTelemetry has the concept of a span link for exactly this: the consumer starts a new root span and attaches a link to the producer's span context, which it reads from the message headers.

The two traces are then navigable from each other in the backend, and each one's duration is meaningful.

Spring Kafka's observation support writes the producer's context into the headers automatically, and the consumer observation reads it; whether it becomes a parent or a link is a configuration choice, and I choose link for anything that is not a synchronous request-reply.

The original trace id still travels as a header for log correlation, so searching logs by the checkout's trace id finds the consumer's lines too.

two traces with a linkruns offline
# illustrative output
trace T1  POST /checkout      12:00:00  producer span p-1
trace T2  consume OrderPlaced 12:05:00  link -> T1/p-1   ✓ each duration is meaningful, each trace navigable

Q92 · Scenario. "A trace for a single checkout shows 40 spans across 14 services and takes 3.1 seconds. Nothing is failing. The product owner wants it under one second. What do you look at, and what do you tell them?"

Reveal answer

The real test Whether you read the waterfall for the critical path rather than the hop count, and whether you say when the architecture itself is the cost.

Strong answer First I would read the waterfall for its shape, not its count.

The evidence: which spans are on the critical path (the chain of spans that must finish before the response can be sent), which run in sequence that could run in parallel, and which are repeated.

Typical findings, ranked by how often they appear:

  1. Serial calls: calls with no data dependency on each other run in sequence — fetch customer, then address, then cart, each 60 milliseconds, when they could be one concurrent fan-out.
  2. N+1: a loop calls pricing once per item, so a ten-item cart is ten hops.
  3. Chatty calls: data fetched again that was already in the request or could be carried in the token.
  4. One slow span nobody suspected, three hops deep.

The fixes in the same order: parallelise independent calls, batch the per-item calls into one, carry data forward instead of refetching it, and treat the slow span as its own investigation. That usually gets from 3.1 seconds to well under a second.

Then the honest part for the product owner: forty hops means the boundaries are too fine for this flow, and beyond the quick wins the durable fix is to merge the services that always appear together on this path, or to precompute a checkout view so the request does less.

The number I would give them is the critical path after the quick wins, with the merge as the next project if that is not enough.

Picture it The 3.1-second waterfall of one checkout as a text timeline, then the same flow with independent calls parallelised and per-item calls batched.

Make the invisible visible: one line per span on the critical path, in milliseconds; the sums are the point.

waterfall beforeruns offline
# illustrative output
auth 100 | customer 60 | address 60 | cart 60 | pricing x10 (10 x 40 = 400) | inventory 300
| payment 400 | shipping 250 | tax 150 | fraud-score 1,180 (three hops deep) | confirm 140
sum on the critical path = 100+180+400+300+400+250+150+1,180+140 = 3,100 ms   ✗

The setup: three independent lookups called in sequence, and a loop calling pricing once per item.

sequential coderuns offline
Customer c = customers.get(id);            // 60 ms   ❌ TRAP: no data dependency between these three,
Address a = addresses.get(id);             // 60 ms      so 180 ms where 60 would do
Cart cart = carts.get(id);                 // 60 ms
for (Item i : cart.items()) prices.get(i); // ❌ TRAP: N+1, ten hops for ten items

What you see now: after parallelising, batching, and fixing the slow span.

waterfall afterruns offline
auth 100 | fan-out customer/address/cart 60 | pricing batch 50 | inventory 300 (fraud-score 180 in parallel)
| shipping 250 (tax 150 in parallel) | payment 400 | confirm 140
sum = 100+60+50+300+250+400+140 = 1,300 ms    ✓ floor now set by payment and inventory

Land it The trace tells you which hops are serial, repeated, or unnecessary, and when the answer is "the architecture", a senior engineer says so with a plan rather than a shrug.

Likely follow-ups
"How do you find the critical path in a 40-span trace without eyeballing it?"

By walking the tree from the root and, at each span, following the child that ends last.

Formally: the root's critical path is the root's own time plus the critical path of whichever child finishes latest, recursively, and any child that overlaps entirely with a later-finishing sibling contributes nothing to it.

Some trace backends compute this — Jaeger has a critical path view and Grafana Tempo can highlight it — and if mine does not, a short script over the exported trace JSON does it in twenty lines.

The output is the ordered list of spans that actually delay the response and the sum of their self-time. In a 3.1-second trace it is common to find that the critical path is eight spans totalling 2.8 seconds and the other thirty-two are parallel or trivial.

critical path walkruns offline
root 3,100 ms
  children: auth, customer, address, cart, pricing x10, inventory, payment, shipping, tax, fraud-score, confirm
  rule: at each level follow the child that ends last, add its self-time, recurse
  fraud-score ends last (at 2,960 ms) -> it is on the path with everything before it
  a child that overlaps a later-finishing sibling contributes 0

That list is what I put in front of the team, because it turns "fourteen services are slow" into "these three calls in sequence are slow".

"Parallelising the independent calls — how do you do it safely in Java, and what does it cost?"

With structured concurrency, or with CompletableFuture if I must stay on an older pattern.

As of Java 25, StructuredTaskScope lets me fork the customer, address, and cart lookups as subtasks, join with a deadline, and get all three results or a single failure, with the guarantee that no subtask outlives the scope.

On virtual threads the fan-out costs almost nothing in threads. With CompletableFuture I use a bounded executor and allOf with orTimeout, and I have to be careful that the executor is not the servlet thread pool.

The costs are real: three concurrent calls put three times the instantaneous load on the downstreams, the bulkhead sizing has to account for the fan-out, and the trace context must be propagated into each subtask or the spans become orphans.

fan-out with CompletableFutureruns offline
var c = CompletableFuture.supplyAsync(() -> customers.get(id), ex);   // ex: bounded, not the servlet pool
var a = CompletableFuture.supplyAsync(() -> addresses.get(id), ex);
var k = CompletableFuture.supplyAsync(() -> carts.get(id), ex);
CompletableFuture.allOf(c, a, k).orTimeout(300, TimeUnit.MILLISECONDS).join();   // 180 ms -> 60 ms

The critical path drops from 180 milliseconds to 60. I would confirm the improvement with the same trace query before and after.

"What number do you commit to with the product owner, and what if you cannot reach one second?"

I commit to a number I have measured, not one I hope for.

After the quick wins in staging, I have a new trace with a new critical path — say 1.3 seconds — and that is the number I give, with the breakdown of what remains: 400 milliseconds in payment authorisation that we do not control, 300 in inventory, and so on.

If the floor is above one second because of an external provider, I say so and offer the design options that change the flow rather than the code: authorise payment asynchronously and confirm the order after, or reserve inventory earlier in the flow so it is not on the confirm step.

Each has a product cost — the customer sees "processing" — and it is their decision. What I refuse to do is promise one second and then explain in three weeks why it is 1.3.

A product owner can plan around an honest 1.3; they cannot plan around a surprise.

"The fix didn't work — you parallelised and batched, and the trace is still 2.5 seconds. Now what?"

Then the trace is not telling me the whole story, and I look for time that is not in any span.

The first suspect is the gap between spans: if the parent span is 2.5 seconds and its children sum to 1.2, the missing 1.3 seconds is in the parent's own process — garbage collection pauses, thread pool queueing before the handler ran, connection pool wait, or serialisation of a large response.

gap in the parent spanruns offline
# illustrative output
parent span 2,500 ms   children sum 1,200 ms   unexplained 1,300 ms
check at that timestamp: GC pause metric, HikariCP pool.Wait, executor queue time

I check the service's GC pause metric and HikariCP wait time for that timestamp. The second suspect is a span that is not instrumented: a call through a client library without tracing, a synchronous cache lookup, a lock.

A thread dump or a profiler sample during a slow request shows where the thread actually was. The third is that the slow part is the network itself — a cross-zone hop or the mesh proxy.

I add spans until the gap is explained, because a trace with unexplained gaps is a hypothesis, not a diagnosis.

Q93 · Design. "The platform handles 50,000 requests a second. Design the trace sampling so that every slow or failed request is kept, the bill is under control, and you can still debug a normal request."

Reveal answer

Strong answer Requirements: 100% of errors and slow traces retained; a representative sample of healthy traces; tracing cost under a set budget; no service needs to know the policy.

The two mechanisms: head sampling decides at the start of a trace, at the gateway, whether to record it — cheap, but it cannot know the trace will be slow; tail sampling decides after the whole trace is complete, in the collector, with full knowledge, but it must buffer every span until then.

Design:

  1. Record everything: the services record every span (sampling probability 1.0) and export to a tier of OpenTelemetry Collectors.
  2. Route by trace id: a load balancer sends all spans of one trace to the same collector.
  3. Decide at the tail: the collector's tail-sampling processor keeps 100% of traces with an error status or a duration over the path's SLO threshold, keeps 100% of traces with a debug header set by engineers, and keeps a 2% random sample of the rest.

At 50,000 requests a second with about 20 spans each, that is a million spans a second into the collectors and perhaps 40,000 a second stored — affordable.

Metrics are derived from the full stream before sampling (span metrics in the collector) so latency percentiles are not biased by sampling. Trade-offs: collector memory to buffer traces for a few seconds, and a decision delay.

What I would not do is head-sample at 1% and hope the outage's requests were in it.

Picture it Four traces arriving at the tail-sampling collector, the decision for each, and the volume arithmetic for 50,000 requests a second. See Pattern: Distributed tracing.

The trace: one decision per complete trace, after the 10-second wait.

tail-sampling decisionsruns offline
trace  duration  status  debug  policy that matched        decision
A       140 ms   ERROR    no    status_code                keep   ✓
B       120 ms   OK       no    only the 2% dice           drop (98 of 100)
C     1,400 ms   OK       no    latency > 800 ms           keep   ✓
D       200 ms   OK      true   string_attribute debug     keep   ✓

Make the invisible visible: the volume at each stage, so the bill is a number.

volume arithmeticruns offline
# illustrative output
50,000 req/s x 20 spans = 1,000,000 spans/s into the collector tier
errors 0.5% + slow 1% + debug ~0 = 750 traces/s kept;  2% of the other ~49,250 = 985 traces/s
kept ~1,735 traces/s x 20 = ~35,000 spans/s stored   (3.5% of the stream)
span metrics computed before sampling: p99 uses all 1,000,000 spans/s  ✓

Land it Record everything, decide at the tail, and derive the metrics before you drop anything — that keeps every interesting trace and most of the budget.

Likely follow-ups
"What does the collector's tail-sampling configuration actually look like, and what are its knobs?"

The OpenTelemetry Collector's tail_sampling processor has three knobs:

  • decision_wait: how long it buffers a trace after the first span arrives before deciding. I set 10 seconds, long enough for a checkout to complete.
  • num_traces: a cap on how many traces sit in memory at once.
  • Policies: a list evaluated in order.

My four policies keep any trace with an ERROR span, any trace slower than 800 ms, any trace with a debug attribute of true, and 2% of the rest.

collector configruns offline
processors:
  tail_sampling:
    decision_wait: 10s
    num_traces: 100000          # per collector
    policies:
      - { name: errors,   type: status_code,      status_code: { status_codes: [ERROR] } }
      - { name: slow,     type: latency,          latency: { threshold_ms: 800 } }
      - { name: debug,    type: string_attribute, string_attribute: { key: debug, values: ["true"] } }
      - { name: baseline, type: probabilistic,    probabilistic: { sampling_percentage: 2 } }

The processor is preceded by a load-balancing exporter tier that routes by trace id so one collector sees all of a trace's spans.

The memory per buffered trace is roughly the span count times a kilobyte, so at 50,000 traces a second and 10 seconds of wait that is half a million traces in memory across the tier, about 10 gigabytes — which is why it is a tier and not one box.

"Why is tracing at 100% in the service acceptable? Doesn't that cost more than the sampling saves?"

The expensive part of tracing is storage and indexing, not creation.

Creating a span is microseconds and the batch exporter sends compressed OTLP over gRPC in the background, so a service exporting every span pays a small CPU cost and some network — at 20 spans a request and 500 bytes a span, 50,000 requests a second is about 500 megabytes a second across the whole platform, which is meaningful but well within cluster-internal bandwidth.

What that buys is the ability to make a decision with full information. The alternative, head sampling at 2%, would save the export cost but keep only one in fifty of the slow and failed requests, which are the ones I actually need.

If export bandwidth ever became the constraint, the middle path is head sampling at a higher rate — say 20% — combined with tail sampling on what arrives, plus a rule that any span with an error forces its trace to be sampled at the head where possible.

"How do you debug a normal request that was not in the 2% sample?"

Two ways. First, the debug header: an engineer reproducing a customer's issue sets x-debug-trace: true on the request, the gateway turns that into a span attribute, and the tail policy keeps it at 100%. That covers reproduction.

Second, for a request that already happened and was dropped, the logs still exist: every log line carries the trace id regardless of sampling, and the log pipeline keeps a sample of its own, so I can often reconstruct the path from logs even without the trace.

The span metrics derived in the collector before sampling also tell me what that endpoint's latency distribution looked like at that minute.

What I cannot do is show the waterfall for a specific unsampled healthy request from yesterday, and I say that plainly: the design trades that for cost.

If a class of requests turns out to need full coverage — say, anything from a partner key — I add a policy for it, which is a configuration change, not a redeploy.

"The requirement changes: legal says trace data may contain personal data and must be deletable per user. What changes?"

Two things. First, the data must not be there in the first place: a collector processor — the attributes or redaction processor — strips or hashes attributes that could carry personal data, such as email, name, or free-text query parameters, before storage.

The service template forbids adding request bodies as attributes. Second, what remains has to be findable by user: a user id attribute is allowed, hashed with a keyed hash so it is not directly identifying but can be looked up for a deletion request.

Then deletion is a query in the trace backend deleting by that hash — which most backends support only by dropping whole blocks, so I would also shorten retention for traces to something like 14 days and rely on metrics for anything longer.

What I would push back on is the idea that traces must be fully anonymous, because a trace with no user id cannot answer "what happened to this customer", which is the question support asks most.

"What would you cut under time pressure?"

The load-balancing tier and the tail sampling, temporarily, in favour of head sampling with one twist.

I would set the head sampler at 10% at the gateway, propagate the sampled flag in traceparent, and add a rule in every service that a span with an error status forces its own trace to be recorded regardless of the flag — OpenTelemetry's ParentBased sampler with a custom root sampler does this in a few lines.

That keeps 10% of everything and all errors, misses slow-but-successful traces, and needs no collector buffering. Span metrics in the collector still come from the full stream, because the metrics connector runs before the sampling decision. That gets me to a controlled bill in a day.

Tail sampling and the latency policy come in the second iteration, once the collector tier is sized and the routing by trace id is tested. What I would not cut is the debug header, because it costs nothing and it is what engineers use most.

Q94 · Scenario. "Traces stop at the order service. The payment and inventory spans exist but appear as separate, parentless traces. What broke?"

Reveal answer

Strong answer The symptom is downstream spans that exist but do not link. That means the trace context was not propagated at one boundary.

The spans are created, so instrumentation is on. They have no parent because the header or message header is missing or unreadable.

Evidence to collect:

  • Capture an outbound request or message from the order service and look for traceparent.
  • Check the propagation format on both sides.
  • Check what sits between them.

Causes, most likely first:

  1. Outbox relay: the order service publishes through the outbox, and the relay that sends the Kafka message runs on a scheduler thread that has no request context. The message goes out without trace headers. This is the most common cause when an outbox is involved.
  2. Format mismatch: one side uses W3C and the other B3 (Zipkin's older format), so the header is ignored.
  3. Lost thread context: a custom thread pool or an @Async method does not propagate context.
  4. Proxy: a proxy strips unknown headers.

The fix for the outbox case has three steps:

  1. Store the trace context in the outbox row at insert time.
  2. Have the relay inject it into the message headers.
  3. Let the consumer link to it. Use a "follows-from" link rather than a parent, since the consumer runs later.

For the others, configure one propagation format everywhere. Wrap executors with Micrometer's context-propagating decorators.

Prevention: a contract test that asserts an outbound message carries trace headers.

Picture it One order's trace id followed through three services shows the exact hop where it disappears. The patterns are distributed tracing and the outbox.

The setup: The order service writes the order and an outbox row in one transaction. A relay on another thread publishes the row to Kafka, and payment consumes it.

Make the invisible visible: The outbox row is written on the request thread, so it is the last place the trace id can be saved. Here it is not saved.

outbox table, before the fixruns offline
outbox
id | aggregate_id | type         | trace_context | sent
17 | 42           | OrderCreated | NULL          | false   ✗ nothing to inject later

The trace: One line per step, with the trace id each lane sees.

sequence lanesruns offline
# illustrative output
step  lane                      what happens                             trace id
1     Order (request thread)    POST /orders arrives                     4bf92f35…
2     Order (request thread)    INSERT orders 42 + outbox 17, commit ✓   4bf92f35…
3     Relay (scheduler thread)  polls outbox, there is no current span   none ✗
4     Kafka                     record key=42, headers = []              none ✗
5     Payment (listener)        starts a new root span                   9c1e7d0a… ✗

What you see: The order log carries one trace id and the payment log carries another, so a search by id finds only half the story.

log lines with trace idsruns offline
# illustrative output
order-service    traceId=4bf92f3577b34da6a3ce929d0e0e4736  Order 42 saved
order-service    traceId=-                                 Relay sent OrderCreated 42 to topic orders
payment-service  traceId=9c1e7d0a22b14f55b2d8c4a1e7f03a96  Authorising payment for order 42   ✗ new trace

span tree (backend):  trace 4bf92f35…  POST /orders -> INSERT      (ends here)
                      trace 9c1e7d0a…  payment.authorise           (parentless)

Why: The scheduler thread never ran inside the request, so there was no current span to read, and nothing was stored in the row for it to find later.

The fix: Save the context in the row at insert time. The relay puts it into the record header and links to it.

outbox with trace contextruns offline
ALTER TABLE outbox ADD COLUMN trace_context text;  -- ✅ FIX: filled on the request thread
-- INSERT INTO outbox (aggregate_id, type, payload, trace_context)
-- VALUES (42, 'OrderCreated', '{...}', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01');

What you see now: Same layout as before: the header is present and the payment trace links back.

log lines with trace idsruns offline
# illustrative output
outbox row 17: trace_context=00-4bf92f35…-00f067aa…-01   ✓
order-service    traceId=4bf92f3577b34da6a3ce929d0e0e4736  Relay sent OrderCreated 42 (span links to 00f067aa…)
payment-service  traceId=9c1e7d0a22b14f55b2d8c4a1e7f03a96  Authorising payment for order 42   ✓ link -> 4bf92f35…

Land it A parentless downstream trace means the context was dropped at one hop, and the outbox relay is the usual hop because it runs on a thread that never saw the request.

Likely follow-ups
"Show me exactly how the outbox row carries the trace context and how the relay uses it."

The outbox table gets a trace_context column, text, filled at insert time by serialising the current span context.

In Micrometer Tracing that is tracer.currentSpan().context() rendered as the traceparent string. If tracestate is present, it is stored too, as a small JSON object.

Because the insert happens inside the request's transaction on the request thread, the context is available.

The relay runs on its scheduler thread. It reads the row and parses the stored traceparent, then does two things:

  1. It sets that context as a link on the span it creates for the send.
  2. It writes the header into the Kafka record's headers as traceparent so the consumer can read it.

In Spring Kafka the consumer's observation picks up the header automatically.

The result in the backend is a producer-side trace with a send span that links to the original request, and a consumer-side trace that links back, with all three sharing the searchable trace id in their logs.

"How do you tell a format mismatch from a dropped header quickly?"

By capturing one outbound message and one inbound request and reading the raw headers. For Kafka I use kafka-console-consumer with --property print.headers=true on the topic and look for traceparent versus b3 or X-B3-TraceId.

kafka-console-consumer, print.headers=trueruns offline
# illustrative output
traceparent:00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01   {"orderId":42,...}   <- W3C, present ✓
b3:4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-1                {"orderId":42,...}   <- B3 only: mismatch if receiver is W3C-only
NO_HEADERS                                                             {"orderId":42,...}   <- dropped on the producer side ✗

For HTTP I enable request logging on the receiver for a minute or use a mesh access log that prints headers. If the header is absent, the context was dropped on the producer side, and the outbox relay or an executor is the suspect.

If it is present but in B3 format and the receiver is configured for W3C only, it is a mismatch; the receiver silently starts a new trace.

The Spring Boot property that controls this is management.tracing.propagation.type, which accepts W3C, B3, or B3_MULTI. I set it to W3C across the platform.

During a migration from B3, the consumption setting can be a list, so a service reads both while producing one.

"Why a link rather than a parent — what goes wrong if you make the consumer a child?"

Three things.

The duration lies: a parent span's trace is not complete until all children end, so a consumer that processes the message a minute later makes the checkout trace appear to take a minute, and any latency alert or SLO derived from trace duration becomes wrong.

The backend may have already finalised the trace: tail sampling waits ten seconds, and a child span arriving after that either starts a new partial trace or is dropped.

And the tree becomes unbounded: a message that fans out to five consumers, each publishing further messages, produces a trace with hundreds of spans over hours. A link keeps each trace's duration honest, lets each be sampled on its own merits, and preserves navigation between them.

The cost is that "show me everything that happened because of this checkout" is a graph walk across linked traces rather than one waterfall, which the backend supports but which is a slightly less pretty picture.

"The fix didn't work — you stored the context in the outbox and the consumer's trace still has no link. What is left?"

Then the header is present on the message but the consumer is not reading it, and I look at the consumer side.

The usual cause is that the listener is a batch listener — @KafkaListener(batch = "true") — and the observation is created for the batch, not per record, so per-record headers are not consumed as parents or links; the fix is to extract the context per record in the handler and start a span manually with a link.

The second cause is that the consumer runs an older Spring Kafka where observation is off by default — spring.kafka.listener.observation-enabled=true is required as of 3.x. The third is a custom RecordInterceptor or deserialiser that drops headers.

I confirm by adding a one-line log of record.headers() in the listener; if traceparent appears in the log and not in the trace, it is the consumer's instrumentation, and if it does not appear, something in between — a stream processor, a mirror — stripped it.

listener log checkruns offline
# illustrative output
header present, trace missing  -> consumer instrumentation:   log: headers=[traceparent=00-4bf92f35…-01]  but trace has no link ✗
header absent in the log       -> stripped in between:        log: headers=[]   (stream processor or mirror) ✗

Q95 · Design. "Define the SLOs and alerts for the checkout path, which crosses six services. Cover the indicators, the objective, the error budget, and the burn-rate alerts."

Reveal answer

Strong answer Three requirements drive the design:

  1. Measure what the customer experiences, not what each service reports.
  2. Page only when the customer is being hurt at a rate that matters.
  3. Give teams a budget to spend on risk.

Indicators, measured at the gateway for the checkout endpoints:

  • Availability: the fraction of requests that return a non-5xx within 2 seconds, so a slow success counts as a failure.
  • Latency: the fraction of requests under 800 milliseconds.

Objectives: 99.9% availability and 95% under 800 milliseconds, both over a rolling 30 days.

Error budget at 10 million checkouts a month: 10,000 failed or slow requests.

Alerts are on burn rate, the ratio of the current failure rate to the rate that would exactly spend the budget over the window. Two windows avoid noise:

  • Page: burn rate over 14 for the last hour and also over 14 for the last 5 minutes. The budget would be gone in about two days, and it is still happening now.
  • Ticket: burn rate over 2 for the last 6 hours.

Internal services get derived budgets. Payment, on the critical path, gets 99.95% so checkout has room for everything else.

Dashboards show the budget remaining. When it is below 25%, feature deploys on the path need a reliability review.

Trade-offs: SLOs need reliable edge metrics and a team willing to honour the budget policy. What I would not do is alert on per-service error counts; they page constantly and say nothing about customers.

Picture it The budget arithmetic and one incident minute by minute show why two windows page at the right moment and not before or after.

The setup: The checkout SLO is 99.9% over 30 days, with 10 million checkouts a month.

error budget arithmeticruns offline
SLO 99.9%            -> allowed bad = 0.1%
10,000,000 requests  -> budget = 10,000 bad requests per 30 days
30 days = 720 h      -> about 13,889 requests per hour, about 1,157 per 5 minutes
burn rate 1          -> spends the 10,000 in 720 h
burn rate 14.4       -> spends it in 720 / 14.4 = 50 h, and 2% of it (200 requests) every hour
page threshold       -> error rate over 14.4 x 0.1% = 1.44%

The trace: Baseline error rate is 0.05%. From 10:00 a bad deploy fails 5% of checkouts and is fixed at 10:25.

burn rate over timeruns offline
# illustrative output
time   5m burn   1h burn   both over 14.4?   action
10:05    50.0       4.6        no             -
10:10    50.0       8.7        no             -
10:15    50.0      12.9        no             -
10:20    50.0      17.0        yes ✓          PAGE (1h window finally big enough)
10:25     0.5      21.1        no             no page ✓ (5m window is clean, the incident is over)
budget spent by 10:25: about 293 of 10,000 = 2.9%

What you see: A single window would fail one way or the other: the 1-hour window alone keeps paging at 10:25 after the fix, and the 5-minute window alone pages on every blip.

The fix: The alert uses both windows, with the 14.4 threshold from the SLO.

burn-rate alert ruleruns offline
- alert: CheckoutBudgetBurnPage
  expr: |
    checkout:error_ratio:rate1h > (14.4 * 0.001)   # ✅ long window: big enough to matter
    and
    checkout:error_ratio:rate5m > (14.4 * 0.001)   # ✅ short window: still happening now
  labels:
    severity: page

Land it Measure at the edge, page on burn rate with two windows, and hand internal teams a slice of the budget, so alerts mean customers and budgets mean decisions.

Likely follow-ups
"Where does the burn rate of 14 come from, and why two windows?"

Burn rate is the failure rate divided by the rate that would spend exactly the whole budget over the SLO window.

With a 30-day window, a burn rate of 1 spends the budget in 30 days; a burn rate of 14.4 spends it in about 50 hours — two days — which is the level where a page during the night is justified because by morning a meaningful slice of the month's budget is gone.

Google's SRE workbook uses 14.4 for the one-hour page and 6 for the six-hour one. Two windows solve two problems.

The short window, five minutes, makes sure the problem is still happening now, so a page does not fire for an incident that ended forty minutes ago. Both must exceed the threshold to page.

I derive the exact thresholds from the SLO, not from memory: for 99.9% the one-hour page at burn rate 14.4 corresponds to a 1.44% error rate.

"How do you measure 'checkout' at the gateway when it is six requests across a session?"

The SLI is defined on the request that represents the customer's intent, not on every request.

For checkout that is the final confirm call, POST /checkout/{id}/confirm. If that succeeds within the latency target, the customer bought something.

The earlier steps get their own, looser SLOs or are folded into a page-load SLO. Measuring at the gateway means the gateway's metrics, tagged by route, are the source: a histogram of duration with a status label.

The 2-second and 800-millisecond thresholds are expressed as histogram buckets so the ratio "requests under 800 milliseconds" is a single PromQL expression over _bucket series.

If a whole-journey SLI is wanted — did the customer get from cart to confirmation — that comes from a session-level event the front end emits, which is a product metric and lives in a different pipeline.

I keep the request-level SLI as the paging one because it is unambiguous.

"The payment team says 99.95% is impossible because their provider is only 99.9%. What do you do?"

I take the number seriously and redo the arithmetic, because an SLO nobody can meet is worse than none.

availability arithmeticruns offline
provider 99.9%  x  payment code 99.95%  = 99.85%      -> below the 99.95% target ✗
two providers, independent failures, failover works:
  1 - (0.001 x 0.001)                    = 99.9999%    -> the target becomes reachable ✓

If the provider is at 99.9% and payment's own code adds its own failures, payment's achievable availability is below 99.9%. A 99.95% target is then fiction.

The options are to change the design or change the budget.

The design options:

  • Add a second provider with failover, which raises the combined availability well above either one.
  • Make the confirm step succeed when the provider is slow, by accepting the order and authorising asynchronously. That moves the provider off the SLI's critical path.

Budget: accept that checkout's SLO is bounded by its weakest critical dependency and set it at 99.9% overall with payment at 99.9% and everyone else higher.

I would present both to the product owner as a cost choice: a second provider costs integration work and money, a lower SLO costs some customer trust. What I would not do is keep 99.95% on paper and watch the budget be permanently exhausted.

"What would you cut under time pressure?"

The derived per-service budgets and the deploy-gating policy, which need organisational agreement, and the six-hour ticket alert.

I would ship the two SLIs measured at the gateway and the 30-day objective. The single two-window page at burn rate 14.4 is a Prometheus recording rule and an alert rule, perhaps fifty lines of YAML.

Add a dashboard panel showing budget remaining.

That is enough to stop paging on per-service error counts, which is the biggest immediate win. I would keep the latency-in-the-availability-SLI definition, because a slow success counted as success makes the whole thing meaningless.

The internal budgets and the "below 25% means a reliability review" policy come after the first month of data.

Then I can show the teams their real numbers, which makes the conversation about targets a conversation about evidence.

Q96 · Design. "Every service gets a default dashboard from the platform template. What is on it, and why those panels?"

Reveal answer

Strong answer The dashboard follows two conventions, and each row answers one incident question.

For each request path, the RED trio: rate, errors, duration.

The first row is requests per second by endpoint, error rate by status class, and latency as p50, p95, and p99. Those three answer "is it busy, is it failing, is it slow" in one glance.

For each resource, the USE trio: utilisation, saturation, errors. The second row is:

  • CPU and memory against limits.
  • Thread-pool active count against its maximum.
  • Database connection pool in-use and wait time.
  • JVM garbage-collection pause time.

Saturation panels are the ones that predict an outage before the error rate moves.

The third row is the service's dependencies. For each outbound client it shows call rate, error rate, latency, and circuit-breaker state.

Most incidents in a service platform are a dependency's incident seen from the caller.

The fourth row is asynchronous work: Kafka consumer lag per topic, dead-letter topic size, and outbox rows unpublished older than a minute.

The last row is deploy markers overlaid on everything, so a change in any panel can be matched to a release.

Every panel links to the trace search filtered to that service and time range.

What I would leave off is anything a team cannot act on: the panel exists to answer a question during an incident, and if no one can name the question, it is noise.

Picture it The default dashboard as rows, then three moments of one incident read off the saturation panels. The dependency row shows the circuit breaker state of each outbound client.

Make the invisible visible: The five rows of the template, each tied to the question it answers.

default dashboard layoutruns offline
row 1  RED      rate | errors by class | p50 p95 p99              "busy? failing? slow?"
row 2  USE      CPU/mem | threads active/max | DB pool wait | GC  "what is about to break?"
row 3  deps     payment: rate err p99 breaker=CLOSED              "is it someone else?"
row 4  async    consumer lag | DLT size | unpublished outbox rows "is work piling up?"
row 5  deploys  ▲ marker per release over every panel            "did my change cause it?"

The trace: Order service, pool of 200 threads, one slow dependency, three moments.

saturation before errorsruns offline
# illustrative output
time   deploy  threads active/max  DB pool pending  p99     error rate  CPU
12:00           45 / 200            0               180 ms   0.1%       35%
12:02  ▲ v1.43  60 / 200            0               200 ms   0.1%       36%
12:03          200 / 200           40               2.4 s    0.1%       30%   <- saturation moves first
12:05          200 / 200          120               8.0 s    9.0%       28%   <- errors follow

What you see: The thread panel hit its maximum two minutes before the error panel moved, CPU stayed low, and the marker sits one minute before the climb. A full pool with low CPU means the threads are waiting, and row 3 names which dependency.

Why: Queueing shows up in saturation panels before it shows up as errors, which is why the second row is where the earliest warning appears.

Land it RED for what users feel, USE for what is about to break, dependencies because that is where incidents come from, and deploy markers because that is what caused them.

Likely follow-ups
"Why p50, p95, and p99 and not the average?"

Because the average hides the shape, and the shape is the diagnosis. A service with an average of 50 milliseconds could be uniformly 50, or 20 for most requests and 2 seconds for a few percent.

Those are different problems with different fixes.

p50 says what the typical user sees. p95 and p99 say what the unlucky users see.

In a platform where one page makes ten calls, the p99 of the dependency is roughly what the p90 of the page looks like, so tail latency compounds across hops.

The average also moves in ways that mislead: a burst of very fast cached responses drops it while real users are timing out.

In practice the panels are computed from a histogram, Micrometer's Timer with percentile histograms enabled. The percentiles are approximations from bucket boundaries.

I set the buckets to match the SLO thresholds so the 800-millisecond line is exact.

I would still show request count on the same panel, because a percentile from twenty requests is noise.

"What is the single saturation panel you would look at first in an incident, and why?"

The thread-pool active count against its maximum, or its equivalent for the runtime — in-flight requests for a virtual-thread or reactive service.

It is the panel that shows queueing before the errors start. When active threads sit at the maximum, every new request waits, latency climbs, and within a minute the timeouts begin.

It also points at the cause, because a full pool with low CPU means the threads are waiting on something — a dependency or the database — and the dependency row below it says which one.

12:03 reading, same incidentruns offline
threads 200/200, CPU 30%      -> threads are waiting, not computing
DB pool pending 40            -> waiting on a connection (look one hop down)
payment row: p99 2.1 s        -> or waiting on the dependency
▲ v1.43 at 12:02              -> started one minute after a deploy: roll back, then investigate

The second panel I look at is the connection-pool wait time, for the same reason one hop down. CPU is third, because in a service platform it is rarely the limit; the limit is usually something the service is waiting for.

The deploy marker overlay is what I check in the same glance, because if the saturation began at a deploy, the investigation is over and the rollback begins.

"How is the dashboard generated, and what stops it drifting from the template?"

It is code, not clicks.

The template contains a dashboard definition: Grafana's JSON model or, better, a Jsonnet or Grafonnet source that parameterises on the service name.

The platform's deploy pipeline renders it and applies it through the Grafana API or a provisioning directory on every deploy.

The service name, its endpoints, and its declared dependencies come from the service's own metadata file, so a new outbound client declared in configuration appears as a new dependency row automatically.

Drift is prevented by ownership. The generated dashboard is read-only and regenerated on each deploy.

A team that wants extra panels adds a second, team-owned dashboard alongside it rather than editing the generated one.

When the template changes — say, a new saturation metric is added — the next deploy of every service picks it up. The check is a nightly job comparing each service's dashboard hash with the rendered template and flagging the differences.

"A team says the dashboard is too much and nobody looks at it. What do you change?"

I would ask which question they could not answer in the last incident, and which panels they used to answer the ones they could.

Usually the answer is that during incidents they used four panels: error rate, p99, pool saturation, and the dependency row. They never looked at the rest.

So the template gets a top row with those four, big, and the rest collapses into folded sections.

The other reason nobody looks is that nothing draws them there: the burn-rate alert should link straight to the dashboard with the time range pre-set, so the first thing an on-call engineer sees is the right panels for the right ten minutes.

And I would add the one thing that makes people open a dashboard voluntarily: the deploy markers, because "did my deploy change anything" is a question every engineer asks and the dashboard is the fastest way to answer it. A dashboard nobody uses is a bug in the dashboard.

Q97 · Scenario. "The p99 latency alert on the order service fires every night between 02:00 and 02:20. p50 is unchanged, error rate is zero, traffic is at its lowest. What is it and should it page anyone?"

Reveal answer

Strong answer A nightly p99 spike with a flat p50 and low traffic is a small number of slow requests. At that hour it is almost always a scheduled job.

Evidence to collect:

  • The traces in that window, sorted by duration.
  • The database's activity at 02:00: a backup, a vacuum, an index rebuild, a nightly batch.
  • What else runs on a schedule: a report, a cache warm-up, a certificate rotation.

Causes, most likely first:

  1. Database contention: a batch job or backup competes for the database, so the few live requests wait on I/O.
  2. Scheduled task in the service: the outbox cleanup or a bulk reconciliation holds locks or the pool.
  3. Low-traffic artefact: at 20 requests a minute, p99 is the single slowest request, so one slow call is the whole percentile.

Fix: if it is contention, move the job or make it gentler, with smaller batches and pauses. If it is the low-traffic artefact, the alert is wrong rather than the service.

Should it page?

No. The alert is measuring a percentile that is statistically meaningless at that volume and no customer is being hurt in a way that matters.

I would change the alert to fire on burn rate against the latency SLO, with a minimum request count, so a percentile computed from a handful of requests cannot page anyone.

I would keep a ticket to fix the contention during working hours.

Picture it What a p99 is made of at 20 requests a minute, with the nightly backup in the same picture.

The setup: Five-minute windows of the order service: about 100 requests at night, two of them slow when the backup starts.

Make the invisible visible: The sorted latencies of one 02:05 window, with the position of each percentile.

one window, sortedruns offline
# illustrative output
requests in window: 98
sorted:  38ms 38ms 39ms ... 41ms 44ms 47ms | 1,880ms 1,910ms
          ^p50 = 40ms                       ^^^^^^^^^^^^^^^^^ 2 requests = 2% of the window
p99 = about 1.9s   (the slowest 1-2 requests decide it)

The trace: The same service across the night, with the database activity beside it.

p99 vs slow shareruns offline
# illustrative output
window  req  slow(>800ms)  p50    p99     slow share  db activity
01:55   102   0            38ms   95ms     0.0%       -
02:05    98   2            40ms   1.9s     2.0%       pg_basebackup running ✗
02:15    97   2            41ms   1.8s     2.1%       pg_basebackup running ✗
02:25   101   0            38ms   90ms     0.0%       -

What you see: The p99 alert fires at 02:05. The latency SLO allows 5% slow requests, so 2% is a burn rate of 0.4, far from a page.

The fix: Alert on the slow ratio and require volume, as in the first follow-up below. A ticket tracks the backup contention.

latency alert guardruns offline
- alert: OrderLatencyBurn
  expr: |
    slow_ratio_5m > (4 * 0.05)                       # ✅ FIX: burn rate 4 on the slow ratio, not a raw p99
    and requests_5m > 100                            # ✅ FIX: no page from a handful of requests

Land it A percentile from twenty requests is not a signal, and an alert that wakes someone for it will be muted by week two — fix the alert and schedule the job.

Likely follow-ups
"How exactly do you add a minimum request count to a latency alert in Prometheus?"

The alert expression multiplies the condition by a count guard. Instead of alerting on histogram_quantile(0.99, ...) > 0.8, I express the SLI as a ratio.

The ratio is the fraction of requests slower than 800 milliseconds over five minutes: 1 - (sum(rate(http_server_requests_seconds_bucket{le="0.8"}[5m])) / sum(rate(http_server_requests_seconds_count[5m]))).

Then I add the guard and sum(rate(http_server_requests_seconds_count[5m])) * 300 > 100, which requires at least a hundred requests in the window before the alert can fire.

That turns "p99 is high" into "more than X percent of at least a hundred requests were slow", which is a statement about customers. The burn-rate form does this naturally because a rate of slow requests is meaningless when there are almost none.

The number 100 is a judgement: it is the smallest count at which one slow request is under 1% of the total and cannot trip the threshold alone.

"Suppose it is the backup contending for I/O. What do you actually change on the database side?"

First I confirm it is the backup. I match the 02:00 start to the backup job's log and look at the database's I/O wait during the window.

Then the fixes, cheapest first.

If the backup runs on the primary, move it to a replica, so the primary's I/O is untouched — most managed databases let the snapshot be taken from a standby.

If it must run on the primary, throttle it. pg_basebackup has --max-rate.

Filesystem-level snapshots are near-instant and shift the I/O to the copy step, which can be rate-limited.

If it is autovacuum or an index rebuild rather than a backup, vacuum_cost_delay and vacuum_cost_limit throttle vacuum, and REINDEX CONCURRENTLY spreads the rebuild.

before and after throttlingruns offline
# illustrative output
before: 02:05  p99 1.9s   iowait 38%   (backup at full speed)  ✗
after:  02:05  p99  120ms  iowait  9%   (backup on a replica, or --max-rate set)  ✓

And I schedule whatever remains at the lowest-traffic minute rather than a round hour, because 02:00 is when every other team's job also runs. The verification is the same p99 panel the next night, with the job's start marked.

"The alert was changed and now nobody was paged when a real 2 a.m. incident happened. What went wrong?"

The alert was tuned for the wrong failure.

If the real incident was a rise in errors rather than latency, the availability burn-rate alert should have caught it independently of the latency one.

If it did not, the availability SLI is not counting the failure. A 401, or a timeout at the gateway that returns 504, might not be in the status classes counted.

If the incident was latency at low traffic and it hurt a real customer, the minimum-count guard is set too high for the night.

The answer is a lower guard combined with a longer window at night, so that fifty slow requests over thirty minutes still register.

What I would not do is revert to the raw p99 alert, because that leads back to the muted pager. I would do the post-mortem on the alert itself: which SLI should have moved, why it did not, and adjust that one. Alerts are code and they have bugs.

"Is there any case where a low-traffic p99 should page?"

Yes: when the few requests are the ones that matter.

A payments callback endpoint that receives twenty webhooks a night is low-traffic, but each one is a settlement.

If all twenty are slow because the database is locked, that is a real problem for twenty real transactions.

For that kind of endpoint the SLI is not a percentile over a window; it is a per-request guarantee, and the alert is on the count of requests over the threshold — "more than three webhook deliveries took over five seconds in the last hour" — with no percentile at all.

The distinction is whether the endpoint's traffic is a sample of customer experience, where statistics apply, or a set of individually important events, where each one counts. The order service's general API at 2 a.m. is the first kind.

The lesson I take is that the alert design depends on what the requests are, and a template alert applied blindly to both kinds is wrong for one of them.

Q98 · Design. "Design the logging pipeline for thirty services: structure, correlation, cost control, and personal data."

Reveal answer

Strong answer Three requirements drive the design:

  • Any incident can be investigated from a trace id to the relevant lines in every service.
  • The bill scales with value rather than with volume.
  • No personal data lands in logs.

Structure: every service emits JSON lines with a fixed schema. The fields are timestamp, level, service name, version, trace id, span id, message, and typed fields.

Spring Boot 3.5+ and 4.x produce this with logging.structured.format.console=ecs. A log agent (Fluent Bit or the OpenTelemetry Collector) on each node ships the lines.

Correlation: the trace id is mandatory in every line, and the log backend links to the trace backend by it.

Cost control works in three layers:

  1. At the source: INFO for business events and WARN and above for everything else. DEBUG is switchable at runtime per service through an actuator endpoint rather than a redeploy.
  2. In the collector: sample high-volume INFO lines, keeping 100% of lines belonging to traces that were sampled as slow or failed and 10% of the rest. Drop health-check noise.
  3. In storage: a hot tier of 7 days for search and a cold tier of 90 days in object storage for compliance.

Personal data has three defences:

  • A logging library that masks known fields (email, card number, address) at the source.
  • A CI check that rejects log statements interpolating user-input objects.
  • A redaction step in the collector as a second line.

Trade-offs: sampled INFO logs mean a normal request's lines may be missing; the trace covers it.

Picture it One order's trace id across four services, what the collector keeps, and a line before and after masking.

Make the invisible visible: Every service writes the same fields, so one search on the trace id returns the whole story.

structured log lines, one trace idruns offline
# illustrative output
{"ts":"10:00:00.012","level":"INFO","service":"gateway","version":"2.4.1","traceId":"4bf92f35...","msg":"POST /orders"}
{"ts":"10:00:00.045","level":"INFO","service":"order","version":"1.43.0","traceId":"4bf92f35...","msg":"order placed","orderId":42}
{"ts":"10:00:00.210","level":"WARN","service":"payment","version":"3.0.2","traceId":"4bf92f35...","msg":"provider slow","ms":1850}
{"ts":"10:00:00.390","level":"INFO","service":"inventory","version":"1.9.0","traceId":"4bf92f35...","msg":"stock reserved","orderId":42}

The trace: The volume arithmetic for a day of logs, stage by stage.

log volume per dayruns offline
# illustrative output
stage                                              GB/day
emitted by 30 services                              1,500
after dropping health-check lines (-20%)            1,200     (WARN+ 120, INFO 1,080)
WARN and above, kept 100%                             120
INFO of slow or failed traces, kept 100%               22
other INFO, kept 10%                                  108
shipped to the hot tier                              ~250     (about one sixth of what was emitted)

What you see: The same line before and after masking. The first is a leak that has to be purged later, the second is safe.

masking at the sourceruns offline
before: {"level":"INFO","msg":"created Customer(name=Ana, email=ana@example.com, card=4111111111111111)"}   ✗
after:  {"level":"INFO","msg":"created customer","customerId":"c-1042"}                                     ✓

The fix: The structured format is a property, and the rest is policy in the agent and the build.

application.ymlruns offline
logging:
  structured:
    format:
      console: ecs        # ✅ one JSON schema in every service

Land it Structured at the source, correlated by trace id, sampled in step with tracing, and masked before it leaves the process — that is a log pipeline you can afford and can show an auditor.

Likely follow-ups
"How does the collector know a log line belongs to a trace that was sampled?"

It does not know at the moment the line arrives, because the tail-sampling decision happens seconds later. Two designs handle it.

The first design accepts a delay:

  1. The log collector buffers lines keyed by trace id for the same ten-second decision window the trace sampler uses.
  2. The trace sampler publishes its decisions to a small shared cache, a Redis set of kept trace ids with a short TTL.
  3. The log processor consults that cache before forwarding or dropping.

The OpenTelemetry Collector does not do this out of the box, so it is a custom processor or a Vector transform with a lookup.

The second design avoids coordination by applying the same policy locally. The log sampler keeps:

  • 100% of lines at WARN and above.
  • 100% of lines whose trace id hashes into the same 2% bucket the trace sampler uses for random selection.
  • 10% of the rest.

That loses the "keep logs for slow traces" property but needs no shared state, and it is what I would start with.

"What does the CI check for personal data in log statements actually look for?"

It is a static analysis rule, and it is deliberately narrow so it does not become noise.

Using ArchUnit or an Error Prone check, it flags any call to a logger method whose argument expression includes an object of a type annotated with the platform's @ContainsPersonalData annotation.

It also flags a field named in a deny-list such as email, phone, cardNumber.

The domain classes for customer, address, and payment carry the annotation, so log.info("created {}", customer) fails the build while log.info("created customer {}", customer.id()) passes.

what the check allows and rejectsruns offline
log.info("created {}", customer);          // ❌ TRAP: Customer is @ContainsPersonalData -> build fails
log.info("created customer {}", customer.id());   // ✅ FIX: passes

A second rule requires that toString() on annotated classes is overridden to mask fields, which catches the exception message path where the object is stringified indirectly.

This does not catch everything — a string built from a masked field elsewhere gets through — which is why the collector's redaction processor exists as the second line, matching regular expressions for email and card formats.

The build check catches the common mistake at the moment the developer makes it.

"Thirty services became a hundred and the log bill tripled. Where do you look first?"

At the top ten log producers by bytes per day, because log volume follows a power law and three services are usually most of it. The log backend's own metrics give that breakdown.

The usual finds:

  • A service logging every request at INFO with the full payload.
  • A consumer logging every Kafka record.
  • A health check logged at INFO every second by every pod.
  • A stack trace logged in a retry loop a thousand times a minute during a dependency slowdown.

Each has a mechanical fix — level, sampling, or a rate limiter on the logger — and the platform can enforce them: a per-service ingestion quota with an alert at 80% and a hard drop at 150%, so a runaway logger costs its own team visibility, not everyone's budget.

The structural fix is to make cost per service visible on the team's dashboard next to latency. When teams can see that they spend more on logs than on compute, the levels get fixed within a week.

"What would you cut under time pressure?"

The trace-correlated log sampling and the two-tier storage.

I would ship four things, which are a day of work if the template is already in place:

  1. Structured JSON with trace ids from the template.
  2. A Fluent Bit agent per node shipping to one backend.
  3. Level discipline at the source.
  4. The masking library.

They give correlation and the compliance basics.

Cost control in the first version is blunt:

  • WARN and above kept forever within retention.
  • INFO kept at 10% by a hash of the trace id.
  • Health-check paths dropped by a filter in the agent.
  • Retention is a single 30-day tier.

What I keep no matter what is the masking at the source and the CI check, because personal data in logs is not a cost problem that can be fixed later — once it is in the backend it has to be found and purged, and that is weeks.

The hot-cold split and the sampler coordination come when the bill justifies them.

Q99. "Why does adding a user id label to a request-count metric take down the metrics system, and what do you do instead?"

Reveal answer

Strong answer A metrics system such as Prometheus stores one time series per unique combination of a metric's labels.

A request counter with labels for endpoint (20 values), status (5), and method (4) is 400 series, which is fine.

Add a user id with a million values and it becomes 400 million series. Every series costs memory for its index and a slot in every scrape.

The server runs out of memory or slows to the point of missing scrapes. That is an outage of the thing you use to see outages.

The same goes for any high-cardinality label: request ids, email addresses, order ids, full URLs with ids in the path.

The rule is that labels are for dimensions you would put in a GROUP BY on a dashboard, with tens of values, not for identifying individual things.

The rule is that labels are for dimensions you would put in a GROUP BY on a dashboard, with tens of values, not for identifying individual things.

For per-user questions, the answer is a different signal: traces and structured logs are built to carry high-cardinality fields, and a log backend can count requests per user for one incident without creating a permanent series for each.

If a per-entity aggregate is really needed — top ten customers by request rate — compute it in a stream processor or in the log backend and export the top-N as a bounded metric.

In Micrometer, a MeterFilter can cap or reject tags to keep a mistake from reaching the registry.

Picture it The series count before and after one extra label, and the code that causes it.

The setup: A request counter in the order service, with one tag added by a well-meaning developer.

request counterruns offline
Counter.builder("orders.requests")
    .tag("endpoint", endpoint)   // 20 values
    .tag("status", status)       // 5 values
    .tag("method", method)       // 4 values
    .tag("user_id", userId)      // ❌ TRAP: 1,000,000 values, one new series per user
    .register(registry)
    .increment();

Make the invisible visible: Each unique label combination is one stored series, so the multiplication is the whole problem.

series countruns offline
# illustrative output
orders_requests_total{endpoint="/orders",status="200",method="POST"}                    1 series
... all combinations without user_id:   20 x 5 x 4                      =         400 series
orders_requests_total{endpoint="/orders",status="200",method="POST",user_id="u-000001"} 1 series
... with user_id:                       20 x 5 x 4 x 1,000,000          = 400,000,000 series

The trace: A few thousand bytes of head memory per series turns the count into a memory bill, and the scrape falls behind.

Prometheus under the bombruns offline
# illustrative output
time   active series   memory     scrape duration   result
10:00        400       1 MB        20 ms             ✓
10:05  2,000,000       6 GB        4 s               ✓ slowing
10:20 40,000,000      OOM kill     -                 ✗ no metrics for the whole fleet

The fix: Remove the label and let a filter reject anything like it. Per-user questions go to traces and logs.

bounded tagsruns offline
Counter.builder("orders.requests")
    .tag("endpoint", endpoint).tag("status", status).tag("method", method)   // ✅ FIX: bounded dimensions only
    .register(registry).increment();
// the user id goes into the trace span attribute and the structured log line

Land it Metrics labels are for a few dozen values you would chart; anything that identifies an individual belongs in traces and logs, and a meter filter is the seatbelt.

Likely follow-ups
"Show me the MeterFilter that would have stopped this."

Two filters, registered as beans so Spring Boot applies them to the registry.

The first rejects a specific tag outright: MeterFilter.deny(id -> id.getTag("user_id") != null). It drops any meter carrying that tag before it is registered.

The second is the general seatbelt, MeterFilter.maximumAllowableTags("http.server.requests", "uri", 100, MeterFilter.deny()).

It caps the number of distinct values for the uri tag on the request metric at a hundred and denies further ones. That catches the common case where a path parameter is not templated and every order id becomes a URI value.

Spring Boot exposes the same cap as management.metrics.web.server.max-uri-tags, which defaults to 100.

I add a log line when a filter denies something, because a denied meter is a bug someone should fix, and a counter of denied registrations on the platform dashboard, because a rising number means a team just shipped a cardinality bomb that the filter absorbed.

"How many series is too many? Give me the arithmetic for one Prometheus instance."

The rule of thumb is that a single Prometheus instance is comfortable at a few million active series and struggling past ten million. Memory is the constraint.

Each active series costs roughly a few kilobytes of memory for its head-block index and samples, so 5 million series is on the order of 10 to 15 gigabytes of RAM before queries.

A platform of forty services with fifty pods each and 500 series per pod is a million series, which is fine.

Add a label with 1,000 values to one metric with 20 existing series per pod. That metric alone becomes 20,000 per pod, 40 million across the fleet, which is beyond any single instance.

Add a label with 1,000 values to one metric with 20 existing series per pod and that metric alone becomes 20,000 per pod, 40 million across the fleet, which is beyond any single instance.

The scrape side fails first: the scrape takes longer than the interval and samples are missed.

I put a per-target series limit in the scrape config, sample_limit: 5000, so a target that explodes is dropped rather than taking the server with it.

I alert on targets hitting the limit.

"The product team genuinely needs per-customer request counts on a dashboard. What is the right pipeline?"

Not Prometheus. Per-customer counts are a high-cardinality aggregation, which is what a columnar analytics store is built for.

The pipeline has three steps:

  1. The gateway emits a structured request log line, or a small event per request, with the customer id.
  2. The pipeline lands it in ClickHouse or a similar store.
  3. The dashboard queries SELECT customer_id, count() ... GROUP BY customer_id over the last hour, which is cheap at billions of rows because the store is designed for it.

If the question is "top ten customers by request rate right now" and it must be a metric, a stream processor computes the top-N every minute and exports ten series with a rank label rather than a customer label, so the cardinality is fixed at ten.

What I explain to the product team is that the metrics system answers "how is the service doing" across a few dozen dimensions in milliseconds, and the analytics store answers "what did this customer do" across millions, and asking either one the other's question is what breaks it.

"What other labels are traps that look harmless?"

The ones that grow slowly. A version label is fine until a pipeline tags every commit hash and a busy service has 300 versions in the retention window.

A pod label is inherent and fine, but a pod label on a metric that already has a uri label multiplies. An error_message label seems bounded until an exception includes an id in its text.

A pod label is inherent and fine, but a pod label on a metric that already has a uri label multiplies. An error_message label seems bounded until an exception includes an id in its text.

A topic label is fine. A partition label on a per-topic consumer metric across a hundred topics with fifty partitions each is 5,000 series per pod.

A tenant label in a platform with ten customers is fine and becomes a bomb when sales signs the thousandth.

The test I apply to every label is whether I can name its maximum number of values, and whether that number is under a hundred. If the answer is "it depends on the data", it is not a label.

Drill · Testing, delivery, configuration and security

This group tests the machinery that lets many teams change many services without breaking each other: contracts, compatible changes, canaries, flags, secrets, and service identity.

Q100. "What does the test pyramid look like for a service platform, and why do end-to-end tests move down the priority list?"

Reveal answer

Strong answer The pyramid has four layers, and the third is the one a service platform adds.

  1. Unit tests: business logic, fast and plentiful.
  2. Service-level integration tests: the service running against its real database and broker in containers (Testcontainers), exercising its API and its consumers, with every external service replaced by a stub: WireMock for HTTP, a local Kafka for events.
  3. Contract tests: each consumer's expectations of a provider are recorded and verified against the provider in the provider's own build, so compatibility is checked without either side running the other.
  4. End-to-end tests: a thin set of business journeys through a deployed environment, plus synthetic monitoring in production, which is the same thing run continuously.

End-to-end tests move down the priority list for four reasons. In a platform of forty services they:

  • Need everything up.
  • Fail for reasons unrelated to the change, such as someone else's deploy or a flaky dependency.
  • Take an hour.
  • Say only that something broke when they fail.

Contract tests give most of the same confidence per boundary in seconds, and they name the consumer that would break.

The rule of thumb: end-to-end tests are smoke tests for the deployment, not correctness tests for the code.

Picture it The same breaking change caught at two layers: a contract test names the consumer in seconds, an end-to-end run finds it forty minutes later. The layer is described in consumer-driven contracts.

Make the invisible visible: The pyramid for a platform of forty services, with what each layer costs and what its failure tells you.

test pyramidruns offline
# illustrative output
layer                          count      run time   a failure tells you
unit                           4,000      40 s       logic in this service
service integration            50/svc     60 s       SQL, migrations, serialisation, listeners
contract (Pact)                30 pacts   30 s       WHICH consumer breaks on this provider change
end-to-end (deployed env)      8 journeys 40 min     "something broke somewhere"
synthetic in production        1 / minute  -         the journey is broken right now

The trace: The payment team renames the response field total to amount. Follow the change through the layers.

one breaking change, two ways to find itruns offline
# illustrative output
payment build:   unit ✓   integration ✓                      (payment tests only itself)
payment build:   provider verification against pacts   ✗     after 14 s
                 -> order-service pact, GET /orders/123: no matching field "total"
without contracts:
staging deploy -> end-to-end suite starts ... 40 min later:
                 -> checkout journey ✗ "expected status CONFIRMED but was PENDING"   (which service? unknown)

What you see: The contract failure names the provider build, the consumer and the field. The end-to-end failure names a symptom, after a deploy to a shared environment.

Why: A contract pins one boundary and runs without the rest of the platform, so it is fast and specific. An end-to-end journey crosses every boundary at once, so it is slow and ambiguous.

Land it Confidence in a service platform comes from testing each boundary's contract in isolation, and end-to-end runs are kept small enough to stay green.

Likely follow-ups
"What does a service-level integration test look like concretely, and how long does it take?"

It is a Spring Boot test that boots the whole application context. Testcontainers supplies PostgreSQL and Kafka, and WireMock stands in for every HTTP dependency.

A test for "place order" sends a real HTTP request to the running application. It asserts the 202 and the row in the orders table.

Then it consumes the Kafka topic with a test consumer and asserts the OrderCreated event with the right key and schema.

A second test publishes a PaymentCompleted event to the input topic and asserts the order's status changes.

The containers start once per test class and are reused across the suite with testcontainers.reuse.enable=true. The fixed cost is fifteen to twenty seconds and each test is well under a second.

integration test (sketch)runs offline
@Test
void placeOrderPublishesOrderCreated() {
    var response = http.post("/orders", body);               // real HTTP, real PostgreSQL, real Kafka
    assertThat(response.status()).isEqualTo(202);
    assertThat(db.query("select status from orders where id = ?", id)).isEqualTo("PENDING");
    var event = kafkaTestConsumer.poll("orders", id);         // the outbox poller really ran
    assertThat(event.key()).isEqualTo(id);                    // ✅ covers SQL, migrations, serialisation, wiring
}

A service's whole suite of fifty such tests runs in about a minute in CI. The test covers exactly what the unit tests cannot: the SQL, the migrations, the serialisation, the outbox poller, and the listener wiring.

"Contract tests only check shape. What about behaviour — who catches a provider that returns the right fields with wrong values?"

The provider's own tests, and that is where the responsibility belongs.

A contract says "when I ask for order 123, I get a 200 with an id, a status string, and a numeric total".

It does not say the total is correct. The consumer has no way to know what correct is, and asserting exact values makes the contract brittle.

Correctness of the total is the provider's business logic, covered by its unit and integration tests. The consumer's contract covers the boundary; the provider's tests cover the inside.

What sits between is semantic drift: the provider changes total from including tax to excluding it, and every contract still passes.

semantic drift passes the contractruns offline
before:  GET /orders/123 -> {"id":"123","status":"PAID","total":119.00}   (includes 19.00 tax)
after:   GET /orders/123 -> {"id":"123","status":"PAID","total":100.00}   (excludes tax)
pact:    id string ✓  status string ✓  total number ✓      -> contract passes, the invoice is wrong ✗

That is caught only by a documented meaning, such as a field description in the OpenAPI schema, and a change process that treats a meaning change as breaking.

That is caught only by a documented meaning — a field description in the OpenAPI schema — and a change process that treats a meaning change as breaking.

Contract tests catch the class of failure that is mechanical and frequent; the semantic class is rarer and needs humans reading a changelog.

"Synthetic monitoring in production — what does it do that the end-to-end suite does not?"

It runs continuously against the real system, which the suite cannot.

A synthetic check is a scripted journey, executed every minute from outside the platform, with its results recorded as metrics. For example:

  1. Log in as a test account.
  2. Add a known product to the cart.
  3. Check out with a test payment method.
  4. Confirm the order appears.

It catches the things that break between deploys: a certificate expiring, a DNS change, a third-party outage, a database filling up.

It also gives a latency measurement from the customer's side of the CDN, which no internal metric has.

The staging suite runs once per deploy and sees a system that is not production. The two share the same journey scripts, so writing the check twice is avoided.

The cost is that synthetic transactions pollute real data unless the platform recognises the test account and excludes it from analytics and inventory — a synthetic=true header that the gateway stamps is the usual mechanism.

"A team says their end-to-end tests catch bugs the contract tests miss. Are they wrong?"

They are probably right, and the question is what kind of bugs.

If the end-to-end tests catch integration bugs between two specific services, such as a field mismatch or an enum value, a contract test is missing for that pair.

The answer is to write it and retire the end-to-end case.

If they catch journey bugs — the order flow works at each hop but the overall state machine reaches a wrong state — that is exactly what the thin end-to-end layer should keep, and the answer is to keep those five tests and make them reliable.

If they catch environment bugs — a misconfigured secret in staging — that is a deployment smoke test, and it belongs in the pipeline as a single health-and-journey check after deploy, not in a forty-minute suite.

I would go through their last twenty end-to-end failures and sort them into those three bins. Usually most are the first kind and a few are the second.

Q101. "Explain consumer-driven contract testing with Pact mechanically: what is recorded, where it goes, who verifies it, and what can-i-deploy answers."

Reveal answer

Strong answer The mechanics run in five steps:

  1. Record: in the consumer's test suite, the consumer's client code runs against a Pact mock server. The test declares the interaction it expects, "given an order exists, when I GET /orders/123, I expect status 200 and a body with id, status, and total", and the mock returns that.
  2. Store: what is recorded is the set of interactions as a JSON pact file: exactly the fields the consumer reads and the status codes it handles, nothing more.
  3. Publish: the consumer's pipeline publishes the pact to the Pact Broker (or the hosted PactFlow), tagged with the consumer's version and branch.
  4. Verify: the provider's pipeline fetches every pact that names it and runs the provider verification. Pact replays each request against the real provider, which supplies "provider states", test hooks that set up "an order exists". The response must satisfy the consumer's expectations by type and shape, not exact values.
  5. Decide: results go back to the broker as a compatibility matrix of consumer version against provider version. can-i-deploy asks that matrix a precise question, and the deploy gate blocks if the answer is no.

The question can-i-deploy asks is: "is provider version X verified against every consumer version currently deployed to production?"

The practical discipline is that consumers record only what they use, so providers can add fields freely and learn exactly who breaks on a removal.

Picture it One pact travelling from the consumer test to the broker, the provider verification and the deploy gate, on the order and payment example. See consumer-driven contracts.

The setup: The order service (consumer) declares what it reads from payment (provider).

consumer testruns offline
@Pact(consumer = "order-service", provider = "payment-service")
V4Pact paymentExists(PactDslWithProvider builder) {
    return builder.given("a payment exists")                       // provider state, a string
        .uponReceiving("get payment 77")
        .path("/payments/77").method("GET")
        .willRespondWith().status(200)
        .body(newJsonBody(b -> {
            b.stringType("id", "77");                              // only the fields order reads
            b.stringType("status", "CAPTURED");
            b.numberType("amount", 49.9);
        }).build())
        .toPact(V4Pact.class);
}

Make the invisible visible: The pact file written by that test is what travels.

pact file (JSON, shortened)runs offline
{ "consumer": {"name": "order-service"}, "provider": {"name": "payment-service"},
  "interactions": [ {
    "description": "get payment 77",
    "providerStates": [ {"name": "a payment exists"} ],
    "request":  {"method": "GET", "path": "/payments/77"},
    "response": {"status": 200, "body": {"id": "77", "status": "CAPTURED", "amount": 49.9},
                 "matchingRules": {"body": {"$.amount": {"matchers": [{"match": "number"}]}}} }
  } ] }

The trace: Time order of the five steps, with where each runs.

sequence lanesruns offline
step  lane                       what happens
1     order-service CI           consumer test runs against Pact mock server ✓, pact file written
2     Pact Broker                pact published, version 7.2.0 of order-service
3     payment-service CI         fetches pacts naming payment, boots once, runs @State hook "a payment exists"
4     payment-service CI         replays GET /payments/77, response has id, status, amount ✓ verified
5     Pact Broker                matrix row stored: order-service 7.2.0 x payment-service 5.2.0 = verified
6     payment-service deploy     can-i-deploy asks: verified against every order-service version in production?

What you see: The matrix after payment 5.3.0 renames amount and the deploy gate answering for it.

matrix and can-i-deployruns offline
# illustrative output
consumer version        provider version     verified   in production
order-service 7.2.0     payment-service 5.2.0   ✓        order-service 7.2.0
order-service 7.2.0     payment-service 5.3.0   ✗ "amount" missing in response body

$ pact-broker can-i-deploy --pacticipant payment-service --version 5.3.0 --to-environment production
-> not verified against order-service 7.2.0 (deployed in production) -> exit code 1, deploy blocked ✓

Land it The consumer writes down what it needs, the provider proves it still provides it, and the broker answers the only deploy question that matters: will anyone in production break.

Likely follow-ups
"What is a provider state, and what goes wrong when it is done badly?"

A provider state is the precondition the consumer's interaction assumes, such as "an order with id 123 exists in status PAID".

It is expressed as a string in the pact. The provider implements it as a setup hook that makes it true before the request is replayed.

In Pact JVM that is a method annotated with @State("an order exists") that inserts the row into the test database. Done badly, it becomes the thing that makes contract tests flaky or meaningless.

Three ways a provider state goes wrong:

  1. The state hook calls real services or a shared database, so the verification depends on the environment and fails randomly.
  2. The consumer writes states so specific that only one exact row satisfies them, so every provider change needs a new hook.
  3. The provider implements the state by stubbing its own repository, so the verification no longer exercises the real query path and a broken SQL statement passes.

The discipline is that states are few, described in domain terms, and implemented against the provider's real persistence in a container.

"What happens when the provider verification fails — who is blocked, and what is the workflow?"

The provider's pipeline is blocked from deploying that version. The broker records the failure against that consumer version, so the failure names exactly which consumer would break.

The workflow depends on why.

If the provider made a genuinely breaking change, there are two ways out. They revert it, or they do the expand-and-contract dance.

That means adding the new shape alongside the old, deploying, waiting for the consumer to migrate, then removing the old.

If the consumer's contract is over-specified — it asserted an exact string where it only needed a type — the consumer relaxes it and republishes, and the provider reruns verification.

Pact has a pending-pacts feature, so a brand-new consumer contract does not block the provider's build until it has passed at least once.

That stops a consumer from blocking a provider by publishing something the provider never agreed to.

Either way the conversation happens in the pull request rather than in an incident, which is the point.

"Does this work for Kafka messages, or only HTTP?"

It works for messages, with the same mechanics and a different shape.

Pact's message pacts let the consumer declare "I expect a message on this topic with these fields and this envelope".

The pact is generated by running the consumer's handler against a message the Pact library builds from the expectation.

The provider verification then calls a provider-side function that produces the message — the same serialisation code that writes to the outbox — and checks the produced payload against the contract.

What message pacts do not cover is delivery: ordering, partitioning, headers, and the topic name are outside the contract, and those are checked by the integration tests.

For a platform with a schema registry there is overlap: the registry's compatibility check protects the schema, and the message pact protects what a specific consumer reads.

I use both, because the registry says "the schema is compatible" and the pact says "this consumer still works". Those are different statements.

A compatible change can still remove a field a consumer needs if the field had a default.

"Thirty consumers, each with a pact. Doesn't verification become slow and the matrix unmanageable?"

Verification of thirty pacts is thirty sets of replayed requests against one running provider, typically a few hundred requests in total, which runs in under a minute; the provider boots once.

The matrix scales because can-i-deploy asks a narrow question — this provider version against the consumer versions currently in production — not the full cross-product.

The management cost is elsewhere. Keeping consumer versions and environments recorded in the broker accurately is a pipeline step on every consumer deploy (pact-broker record-deployment).

The other cost is pruning contracts for consumers that no longer exist.

Where it genuinely gets heavy is a provider with hundreds of consumers, such as a platform identity service.

There I would flip to a provider-driven contract published as an OpenAPI document with a compatibility check, and reserve consumer-driven pacts for the consumers whose usage is unusual. Bi-directional contract testing in PactFlow does exactly that combination.

Q102 · Scenario. "Service B deployed at 10:00. At 10:02, the mobile app — which only ever calls service A — started failing on every order. B's team says nothing in their change touched A's API. Diagnose."

Reveal answer

The real test Whether you can trace a transitive dependency and name the contract that should have caught it.

Strong answer The symptom is a consumer breaking after a deploy of something it does not call. That means a transitive dependency: A calls B, or A consumes B's events, inside the path the mobile app uses.

Evidence to collect:

  • A trace of a failing mobile request, which shows A's call to B and its error.
  • A's logs for the exception.
  • B's diff.

Causes, most likely first:

  1. Response shape: B renamed a field, changed a type, or removed an enum value that A reads. That is a breaking change to A even if B considers it internal.
  2. Event schema: B changed an event schema A consumes.
  3. Tighter validation: A's request, unchanged for months, is now rejected with a 400.
  4. Slower B: B's new version is slower, A's timeout fires, and A has no fallback.

The immediate fix is to roll B back, which is why every deploy must be reversible in minutes.

The real fix is that A's expectations of B were never recorded as a contract, so B's pipeline could not know.

Then three steps close the gap:

  1. Add a consumer-driven contract from A to B, verified in B's build, and gate B's deploy on can-i-deploy.
  2. Make A a tolerant reader so additive changes cannot hurt it.
  3. Classify A's dependency on B as critical or degradable, and add a fallback if it is the latter.

Prevention at the platform level: no service deploys without verifying the contracts of every consumer it has in production.

Picture it Who calls whom, the one failing hop, and the deploy-to-rollback timeline, with the order service as A and payment as B. See consumer-driven contracts.

Make the invisible visible: The mobile app never calls payment, but its request passes through it. The blast radius is every order.

topologyruns offline
Mobile app --> A: order-service --> B: payment-service   (B deployed 10:00)  ✗ 400
                       |
                       +--------> inventory-service                            ✓ untouched
blast radius: every POST /orders from every mobile user, although the app never calls B

The trace: The failing request across lanes, with the status at each hop.

sequence lanesruns offline
# illustrative output
step  Mobile        Order (A)                      Payment (B, v2)
1     POST /orders
2                   validates, builds charge call
3                   POST /payments  (no currency) ->  tightened validation: currency required
4                                                  <- 400 {"error":"currency is required"} ✗
5                   no fallback -> 500
6     <- 500 ✗

What you see: The trace shows the failing hop and the order log names it. The timeline shows how long it stayed broken.

timeline and logruns offline
# illustrative output
10:00  payment-service v2 deployed (rolling, 100%)
10:02  mobile checkout error rate 0% -> 100%
10:09  rollback of payment-service to v1
10:10  mobile checkout error rate back to 0.1% ✓
order-service  ERROR traceId=4bf92f35...  POST http://payment/payments -> 400 {"error":"currency is required"}

The fix: A's pact records the request A really sends, so B's own build would have replayed it.

provider verification in B's build (shape of the output)runs offline
# illustrative output
Verifying a pact between order-service and payment-service
  POST /payments (no currency) ... returned 400, expected 201   ✗   -> deploy of payment 5.3.0 blocked

Land it "We did not touch A's API" is true and irrelevant — B changed B's API, A consumes it, and the missing contract test is the root cause.

Likely follow-ups
"B says it was an additive change — a new required field in the request. Why did that break A?"

Because "additive" means additive for the reader. A new required field in a request is subtractive for the caller: it removes the validity of every request A was already sending.

Additive changes are ones that an existing consumer can ignore:

  • A new optional response field.
  • A new endpoint.
  • A new optional request parameter with a default.

These look like additions in the diff and are breaking:

  • Making a request field required.
  • Tightening validation.
  • Narrowing an accepted enum.

This is exactly what the contract would have caught. A's pact records the request A sends, and B's verification would have replayed that request and received its own new 400.

The rule I state is that a provider may add to what it returns and may loosen what it accepts. Anything else is a breaking change that needs expand-and-contract.

For a new required field that means: accept the field as optional with a default, get A to send it, then make it required.

"The rollback of B is not possible because B's release included a migration. What now?"

Then I fix forward, as fast as I can, and I note that the irreversibility is a second finding for the post-mortem.

Fastest fix: B ships a hotfix that makes the new field optional again with a default. It is a code-only change and takes minutes through the hotfix pipeline.

If that is not possible, A ships a hotfix that sends the field, which is also code-only but puts the burden on the team that did nothing wrong.

Meanwhile, if A has a feature flag around the call to B or a fallback, I turn it on to stop the bleeding.

On the migration itself: a release that cannot be rolled back because of a schema change has broken the expand-and-contract rule from the deployment questions.

That is a separate prevention item. Every migration must be compatible with the previous code version, precisely so that rollback stays available on the day something like this happens.

"How do you find every transitive consumer of B in a platform of forty services?"

From the tracing data, not from documentation. Every span that calls B has a peer service attribute.

A query over the last seven days for distinct calling services on B's endpoints gives the direct callers.

Walking one hop further, to who calls those callers, gives the transitive graph. The trace backend or a small script over its API produces it.

For Kafka, the consumer groups on B's topics, listed with kafka-consumer-groups --describe, give the consumers directly.

A service catalogue such as Backstage should hold this too, but the tracing data is what is true today. Then the important step: every direct caller found this way that has no pact against B is a gap, and I list them.

That list is the real output of the incident — the contracts that do not exist — and it becomes the backlog for the next two weeks, starting with the callers on customer-facing paths.

"What does 'tolerant reader' mean in code, and where does it fail?"

A tolerant reader ignores what it does not understand and copes with what is missing.

In Jackson that is @JsonIgnoreProperties(ignoreUnknown = true) on the response class, or FAIL_ON_UNKNOWN_PROPERTIES disabled on the mapper, so a new field from the provider does not throw.

Optional fields are modelled as Optional or nullable with a sensible default rather than a primitive that fails on null.

For enums, an unknown value maps to an UNKNOWN constant instead of throwing, with @JsonEnumDefaultValue.

tolerant readerruns offline
@JsonIgnoreProperties(ignoreUnknown = true)          // ✅ FIX: a new field does not throw
record PaymentView(String id, String status, Optional<String> currency) {}

enum PaymentStatus {
    CAPTURED, FAILED,
    @JsonEnumDefaultValue UNKNOWN                    // ❌ TRAP on payment status: silently hides a new value
}

Where it fails is semantics. Tolerance cannot make a consumer cope with a field that changed meaning, a status value it has never seen on a path where it must act, or a required field going missing.

And tolerance can hide problems — an enum silently mapped to UNKNOWN in a payment status is worse than an exception.

So I pair it with a metric: a counter of unknown fields and unknown enum values seen, so the tolerance is visible and someone looks when it starts counting.

Q103 · Design. "Design the versioning strategy for a service API with thirty consumers, so that breaking changes are rare, safe, and never a coordinated deploy."

Reveal answer

Strong answer Three requirements drive the design:

  • Most changes ship with no consumer action.
  • The rare breaking change has a migration window.
  • Nobody deploys in lockstep.

The design has three tiers.

Tier 1: make breaking changes rare by rule. Only additive changes ship without a version: new optional fields, new endpoints, new enum values that consumers are required to tolerate.

Consumers are contractually tolerant readers, verified by contract tests.

Tier 2: when a change must break, use expand-and-contract on the same version.

  1. Add the new field or endpoint alongside the old.
  2. Migrate consumers one at a time, with the contract matrix showing who still uses the old.
  3. Remove the old only when the broker shows zero consumers on it.

Tier 3: a new major version for a redesign. It lives at a new path (/v2/orders) served by the same service.

  1. Both versions stay live for a published window, say six months.
  2. Deprecation headers (Deprecation and Sunset) go on v1 responses.
  3. Usage metrics per consumer per version let the window end on evidence rather than hope.

Trade-offs: the provider carries two code paths for a while.

What I would not do:

  • Version by header or media type for internal APIs, because it hides the version from every log and trace.
  • Let a version live forever because the last consumer never migrated. The sunset date is enforced with an escalation.

Picture it A field rename across ten weeks and thirty consumers, and the HTTP headers that announce a retiring version. See consumer-driven contracts for the broker that provides the "who uses it" numbers.

Make the invisible visible: The response body in each phase of renaming total_amount to amount.

response during the renameruns offline
week 0:  {"id":"123","total_amount":49.9}
week 1:  {"id":"123","total_amount":49.9,"amount":49.9}     <- expand: both, same value
week 10: {"id":"123","amount":49.9}                         <- contract: old field gone

The trace: Who still reads the old field, week by week, as the broker matrix shows it.

migration timelineruns offline
# illustrative output
week  provider returns       consumers reading total_amount / amount   action
0     total_amount           30 / 0                                    -
1     both (expand)          30 / 0                                    contract tests still pass ✓
4     both                   12 / 18                                   teams migrate on their own schedule
8     both                    2 / 28                                   stragglers listed, escalated
9     try to remove          can-i-deploy ✗ names the 2 consumers still on total_amount
10    amount only (contract)  0 / 30                                   can-i-deploy ✓, field removed

What you see: A retiring v1 tells every client, in every response, when it will stop working.

v1 response headersruns offline
HTTP/1.1 200 OK
Deprecation: @1735689600
Sunset: Sat, 28 Feb 2027 00:00:00 GMT
Link: </v2/orders/123>; rel="successor-version"

Why: The rename takes ten weeks because thirty teams deploy independently. That is the price of never coordinating a deploy.

Land it Additive by default, expand-and-contract for the rest, a numbered version only for redesigns — and the contract broker tells you when the old one can finally die.

Likely follow-ups
"Walk me through expand-and-contract for renaming a response field from total_amount to amount with thirty consumers."

Expand: the provider adds amount to the response with the same value as total_amount and keeps both. Contract tests pass because consumers only assert on fields they read.

Migrate: each consumer team changes its client to read amount, republishes its pact, and deploys on its own schedule.

The broker's matrix shows which consumer versions in production still have total_amount in their pact.

Nag: after the announced window, say eight weeks, the provider team lists the stragglers from the broker and escalates.

Contract: when the broker shows zero production consumers whose pact mentions total_amount, the provider removes it. can-i-deploy confirms nothing in production breaks.

The whole thing is five to ten weeks for a field rename. That sounds slow and is in fact the speed at which thirty independent teams can move without a coordinated deploy.

A rename that is not worth ten weeks is not worth doing.

"How do the Deprecation and Sunset headers work, and how do you measure who still uses v1?"

They are standard HTTP response headers defined in RFC 8594 and RFC 9745.

Each header does one job:

  • Deprecation: @1735689600, or a date, says the endpoint is deprecated as of that time.
  • Sunset: Sat, 28 Feb 2027 00:00:00 GMT says when it will stop working.
  • A Link header with rel="successor-version" points at v2.

Clients that watch for them — and a service template's HTTP client can log a warning when it sees one — get an automated nudge.

Usage measurement comes from the gateway. Every request is tagged with the API version from the path and the client identity from the token or the mTLS certificate.

A metric of requests per version per consumer is then one PromQL query.

That is the list the sunset conversation uses. When the count for a consumer on v1 reaches zero for two weeks, they are done; when it does not, the number in the escalation email is the number of requests a day they still send.

"Why not version by media type or header? It is what the REST purists recommend."

Because inside a platform the cost of hiding the version outweighs the purity.

A version in the path, /v2/orders, appears in every access log, every trace span name, every metric label, and every gateway routing rule for free.

A version in an Accept header appears in none of them unless someone adds instrumentation for it. Routing by header at the gateway is a custom rule.

Operationally the path version answers "who is still on v1" with a query, and the header version needs a code change to answer it.

For a public API with a long life and a hypermedia design, header versioning has an argument; for thirty internal consumers, the argument is operational visibility, and the path wins.

I do put the version in the path only for genuine major versions, which should be rare — most changes never get one because they are additive or handled by expand-and-contract.

"What would you cut under time pressure?"

The formal deprecation headers and the version-usage dashboards, but not the additive rule or the contract broker. The additive rule is a review guideline and costs nothing to adopt today.

The contract broker and can-i-deploy are the machinery that makes everything else safe, so they stay.

Without them I have no way to know when the old field can go.

What I would defer is the versioned-path infrastructure — gateway routing for /v2, dual code paths — because a well-run additive-plus-expand-and-contract regime avoids needing a major version for a long time.

If a real redesign is forced under time pressure, the cheap version is a new endpoint name rather than a new version prefix, served by the same code base, with the old one left in place and the usage tracked by a plain access-log count until the dashboards exist.

Q104 · Scenario. "A rolling deploy renamed the column total_amount to amount in the order service's database as part of the release. For three minutes, half the requests failed with SQL errors, then it settled. Explain and give the safe procedure."

Reveal answer

Strong answer During a rolling deploy, old and new versions of the service run at the same time against one database.

The migration renamed the column when the first new pod started. The old pods, still serving half the traffic, ran queries naming total_amount and failed until they were replaced.

Evidence to collect: the SQL error text in the old pods' logs, the migration's timestamp, and the rollout's duration.

The rule the deploy broke: every schema change must be compatible with both the previous and the next version of the code, because they overlap.

The same rule keeps a rollback of the code working against the migrated schema.

The safe procedure is expand and contract across at least two releases, in practice three:

  1. Release one (expand): add the new column amount, deploy code that writes both columns and reads the old one, and backfill the new column in batches.
  2. Release two: deploy code that reads the new column and still writes both. Verify.
  3. Release three (contract): stop writing the old column. Only after that release is stable and rollback is no longer needed, drop it in a later migration.

Each step is compatible with its neighbours, so the rolling overlap and any rollback are safe.

Prevention: a review rule and, ideally, a check in the migration tool that flags renames and drops as needing the multi-release pattern.

Picture it The four pods of the order service during the one-release rename, the table at each moment, and the three-release version that never fails. The compatibility rule is the same one that keeps blue/green switches and canaries safe.

The setup: One release renames the column and ships code that reads the new name.

V42__rename_total.sqlruns offline
-- ❌ TRAP: old pods still run "select total_amount from orders"
ALTER TABLE orders RENAME COLUMN total_amount TO amount;

The trace: Four pods, rolling one at a time, with the migration running when the first new pod starts.

rolling deploy timelineruns offline
# illustrative output
time   pods (v1 = old, v2 = new)    column in the table   old-pod requests
09:58  v1 v1 v1 v1                  total_amount          ✓
10:00  v2 v1 v1 v1  (migration)     amount                ✗ 3 of 4 pods fail
10:01  v2 v2 v1 v1                  amount                ✗ 2 of 4 fail   <- half the requests
10:02  v2 v2 v2 v1                  amount                ✗ 1 of 4 fails
10:03  v2 v2 v2 v2                  amount                ✓ settled after three minutes

What you see: The error in the old pods' logs, matching the migration timestamp.

old pod logruns offline
# illustrative output
10:00:07 ERROR  org.postgresql.util.PSQLException: ERROR: column "total_amount" does not exist
10:00:07 ERROR  GET /orders/123 -> 500

The fix: Three releases. Every row of this table is compatible with the code versions on both sides of it.

expand and contractruns offline
-- release 1 (expand): additive only, old code keeps working
ALTER TABLE orders ADD COLUMN amount numeric(12,2);
-- app v1.1: writes both columns, reads total_amount; batch backfill:
-- UPDATE orders SET amount = total_amount WHERE id BETWEEN :lo AND :hi AND amount IS NULL;
-- release 2: app v1.2 reads amount, still writes both            -- ✅ rollback to v1.1 still works
-- release 3 (contract): app v1.3 stops writing total_amount
-- later migration, once v1.3 is stable:
ALTER TABLE orders DROP COLUMN total_amount;                    -- ✅ no running code needs it

What you see now: The same deploy with the expanded schema: no error line at any step.

rolling deploy timelineruns offline
# illustrative output
time   pods                         columns                   old-pod requests
10:00  v2 v1 v1 v1  (migration)     total_amount + amount     ✓
10:03  v2 v2 v2 v2                  total_amount + amount     ✓   zero errors

Land it Old and new code always overlap during a rollout, so a schema change must be readable by both, and a rename is three releases, not one.

Likely follow-ups
"Three releases for a rename is slow. Is there a faster way that is still safe?"

There is a two-release shortcut that uses the database instead of the code for the compatibility layer.

Release one adds the new column and a trigger that mirrors writes both ways. An insert or update to total_amount copies into amount, and the reverse.

Old code writing the old column and new code writing the new column both keep the other current, with no dual-write logic in the application.

The same release deploys code that reads and writes only amount.

Release two drops the trigger and the old column once the previous version is retired. That is two releases, and the trigger costs a few microseconds per write.

The other shortcut is a view. Rename the table, create a view with the old name exposing amount AS total_amount, and old code keeps working through the view.

What is never safe is the one-release rename, and what I would do about the slowness is make releases cheap enough that three of them is a week, not a quarter.

"How would a migration tool flag this automatically?"

With a linter on the migration scripts in CI. Tools such as Squawk for PostgreSQL parse each migration and flag categories of danger:

  • Dropping a column.
  • Renaming a column or table.
  • Adding a NOT NULL column without a default.
  • Adding an index without CONCURRENTLY.
  • Changing a column type.

The rule set is configurable. I set renames and drops to fail the build unless the migration carries an explicit marker that a reviewer checks against the deploy history.

The marker is a comment such as -- expand-contract: step 3 of 3, previous version retired 2026-08-20.

Flyway and Liquibase do not do this analysis themselves, so the linter runs as a separate pipeline step on the migration directory.

It also catches the locking problems: an ALTER TABLE that takes an exclusive lock on a large table is flagged regardless of compatibility, because a three-minute lock is its own outage. The linter does not understand intent; the marker and the review supply that.

"What about the rollback case specifically — the new code is bad and you need the old version back after the migration ran?"

This is the case the expand-and-contract pattern is really for, and it is why the contract step comes last.

After release one, the schema has both columns. Rolling back the code to the previous version puts back code that reads total_amount, which still exists and is still written, so rollback works.

After release two — code reads amount, writes both — rollback to release one is fine for the same reason.

Only after release three, when the old column is dropped, is rollback to a version that reads it impossible.

That is why the drop waits until release three has been stable long enough that nobody would roll back past it, typically a week or two.

The rule is that a migration is applied N releases before the code that requires it, so that there are always N versions of code that work against the current schema.

Down migrations are not part of my rollback plan; they are rarely tested and often lose data.

"The rename is in a table with 400 million rows. What changes?"

The backfill and the locking become the problem rather than the compatibility.

Adding a nullable column is instant in PostgreSQL. Backfilling 400 million rows in one UPDATE holds locks, bloats the table, and can take hours.

Instead the backfill runs in batches of a few thousand rows by primary key range, with a short pause between batches. It is a background job that can be stopped and resumed, and it takes a day.

The trigger approach keeps new writes consistent while the backfill catches up on old rows.

Adding a NOT NULL constraint at the end is done as ADD CONSTRAINT ... NOT VALID followed by VALIDATE CONSTRAINT, which scans without an exclusive lock.

Any index on the new column is created CONCURRENTLY. Dropping the old column is instant in metadata but leaves the space until a vacuum; that is fine.

batched backfill and progress checkruns offline
UPDATE orders SET amount = total_amount
 WHERE id BETWEEN 1 AND 5000 AND amount IS NULL;                 -- ✅ FIX: batch by key range, then pause
SELECT count(*) FROM orders WHERE amount IS NULL;                -- progress; needs a partial index to be cheap
-- Result (illustrative): 399,995,000 ... 120,000,000 ... 0

I would also verify the backfill's progress with a count of rows where amount IS NULL, which needs a partial index to be cheap.

Q105 · Scenario. "A canary ran at 5% for thirty minutes with no error increase, was promoted to 100%, and then 5% of users could not log in. How can a canary miss a 5% failure?"

Reveal answer

Strong answer A canary measures what its traffic slice exercises. The slice can be unrepresentative in ways that hide exactly the failure you have.

Evidence to collect:

  • How the 5% was selected: random per request, per user, or by region.
  • What the failing users have in common.
  • Whether the canary's metrics were compared to the baseline or to an absolute threshold.

Causes, most likely first:

  1. Cohort failure: the failure affects a cohort, such as users with a particular account type, a legacy token format, or an older app version. Per-request random routing at 5% put a handful of those users' requests on the canary, too few to move an error rate.
  2. Stateful failure: it appears only after a user's session touches both versions. A session written by the new version cannot be read by the old, or the reverse. A short canary with request-level routing does not surface it.
  3. Wrong metric: the canary judged only 5xx rates while the failure returned a 401, which counted as success.

Fix for the incident: roll back.

Fixes for the canary:

  1. Route by user rather than by request, so cohorts are exercised whole.
  2. Compare canary metrics against the stable version's metrics at the same moment rather than against a fixed threshold.
  3. Include business indicators, such as login success rate and orders per minute, not only HTTP status.
  4. Run long enough that the stateful interactions happen.

Prevention: a canary is an experiment, and the analysis has to be designed, not just the traffic split.

Picture it The canary timeline with traffic percentages and the moment of rollback, and the two metrics that disagree about the same minute. See canary for the pattern itself.

Make the invisible visible: During the canary, a 5xx judge and a login-success judge look at the same 5% of traffic and give opposite answers.

canary vs stable, same 10 minutesruns offline
# illustrative output
                 stable (95%)    canary (5%)     judge
login attempts   9,500           500
5xx responses    0               0               pass ✓  (5xx rate: 0 vs 0)
401 responses    95              30              (counted as success by the 5xx judge)
login success    99.0%           94.0%           FAIL ✗  (5-point gap vs stable)

The trace: The rollout with its traffic share at each moment.

canary timelineruns offline
# illustrative output
time    canary traffic   decision
10:00    5%              canary starts, judge = 5xx rate only
10:30    5%              no 5xx increase -> promote ✓ (wrong call)
10:31   100%             legacy-token users start to fail login with 401 ✗
10:47   100%             support tickets, login success 94% -> rollback to stable
10:48     0%             login success back to 99% ✓

What you see: The failing users are 5% of all users. At 5% of requests the canary held about 25 of their attempts per ten minutes and the 5xx metric could not see them.

The fix: Judge on the business metric, compared with stable at the same moment, and route by user so a cohort stays whole.

canary analysis metricruns offline
metrics:
- name: login-success-vs-stable
  # ✅ FIX: success ratio of canary minus success ratio of stable, same window
  successCondition: result[0] > -0.01       # canary may be at most 1 point worse than stable
  provider:
    prometheus:
      address: http://prometheus:9090
      query: |
        sum(rate(login_attempts_total{result="success",version="canary"}[5m])) / sum(rate(login_attempts_total{version="canary"}[5m]))
        - sum(rate(login_attempts_total{result="success",version="stable"}[5m])) / sum(rate(login_attempts_total{version="stable"}[5m]))

Land it A canary only finds failures its slice and its metrics can see, so route by user, compare against baseline, and measure the business outcome, not the status code.

Likely follow-ups
"How exactly do you route a canary by user with a mesh, and what if the user is not logged in yet?"

The routing rule hashes a stable identifier and sends a fixed slice of the hash space to the canary.

In Istio that is a VirtualService with a match on a header. The gateway sets x-user-bucket to a value from 0 to 99 computed as a hash of the user id.

A route sends buckets 0 to 4 to the canary subset.

Argo Rollouts and Flagger can drive that rule as the canary steps grow.

For a user who is not logged in yet, the login request itself has no user id. The gateway falls back to a cookie set on first visit, a random session bucket, which keeps the same browser on the same version through login and after.

A login endpoint bug therefore shows up because the whole session is on one version. What I avoid is routing by source IP, which puts an entire office or carrier on the canary and makes the sample lumpy.

"What business metric would have caught this, and how does the canary analysis get it?"

Login success rate: successful logins divided by login attempts, per version, per minute.

It would have dropped from 99% to about zero for the affected cohort.

Even diluted by the unaffected majority on the canary, a 5% cohort failing entirely is a five-point drop. Any comparison against the stable version flags that in a few minutes.

The analysis gets it because the service emits a counter, login_attempts_total with a result label.

It is tagged with the version label the deployment injects. The canary analysis template queries the ratio for the canary and the stable version over the same window.

Kayenta, Argo's analysis templates, and Flagger's metric templates all accept an arbitrary PromQL expression per metric.

The rule for choosing business metrics is that each service names the two things that mean it is working — for identity, logins and token refreshes; for checkout, orders and payments — and the canary judges those first.

"The stateful case — a session written by the new version cannot be read by the old. How do you canary that at all?"

You make the session format compatible first, which is the same expand-and-contract rule as the database, applied to serialised state.

Concretely, the new version must write a session that the old version can still read, by adding fields rather than changing them. It must also read old sessions.

If the format change is genuinely incompatible, such as a different serialiser, the migration is two steps:

  1. Version one reads both formats and writes the old.
  2. Version two, deployed after version one is at 100%, writes the new.

Each step is canaryable because both versions can handle any session they meet.

Routing by user helps but is not enough on its own, because a user can be re-bucketed during the rollout as the canary percentage grows.

The honest rule is that a canary tests a version against live traffic, and if two versions cannot coexist, no traffic split is safe, so the change is restructured until they can.

"The fix didn't work — you route by user and compare against baseline and a similar bug still got through. What else?"

Then the cohort was too small to be visible even with proper routing, or the failure took longer than the canary ran.

For a cohort that is 5% of users, a 5% canary contains about 0.25% of all users who are affected. At low traffic that might be a handful of requests.

There are two fixes:

  • A longer canary at a higher percentage before promotion. 10% for an hour catches more than 5% for thirty minutes.
  • Targeted routing: send the known risky cohorts to the canary deliberately, which is possible if the cohort is identifiable, such as users on the legacy token format or the oldest app version.

For failures that take time, a canary shorter than the delay cannot see them. An example is a token that expires after an hour and cannot be refreshed by the new version.

The answer is a synthetic check that exercises the refresh path against the canary immediately, rather than waiting for real tokens to age.

Q106 · Design. "Design the automated canary pipeline for the platform: traffic steps, duration, the metrics judged, the rollback trigger, and what a human still does."

Reveal answer

Strong answer Three requirements drive the design:

  • Every deploy is watched before it takes full traffic.
  • A bad deploy is reverted automatically within minutes.
  • No engineer has to stare at a dashboard.

Design: on Kubernetes, Argo Rollouts or Flagger manages the rollout and uses the mesh or ingress to split traffic.

Steps: 1% for 5 minutes, 10% for 10 minutes, 50% for 10 minutes, then 100%.

The early steps are small enough to bound harm. The later ones are long enough to see stateful effects.

Routing by user cohort (a hash of the user id) so each user is consistently on one version.

The analysis runs every minute and compares the canary against the stable version at the same time on:

  • Error rate by status class.
  • p99 latency.
  • Two business metrics for the service. For checkout, those are orders completed per minute and payment success rate.

The judgement is statistical. It fails if the canary's error rate exceeds the baseline's by more than a margin with enough samples, not on a single bad minute.

Rollback trigger: any failed analysis, or a manual abort, shifts traffic back to stable within a minute. The failed version is kept for investigation.

Prerequisites: backward-compatible schema and API changes, and the service's metrics tagged by version.

What a human still does:

  • Writes the business metrics for the service.
  • Reviews the analysis result when a rollout is aborted.
  • Decides on changes the canary cannot judge, such as data migrations.

Trade-offs: rollouts take 30 minutes rather than 3; a hotfix path with a shortened schedule exists for incidents.

Picture it The steps of one rollout with the traffic share at each moment, the analysis result at each step, and the abort. The pattern is canary, shown here on the payment service.

The setup: The rollout definition: weights, pauses and the analysis that runs in the background.

Argo Rollouts canaryruns offline
strategy:
  canary:
    analysis:
      templates:
      - templateName: payment-vs-stable     # error rate, p99, payment success, canary vs stable
    steps:
    - setWeight: 1
    - pause: {duration: 5m}
    - setWeight: 10
    - pause: {duration: 10m}
    - setWeight: 50
    - pause: {duration: 10m}              # after the last step the rollout goes to 100%

The trace: A bad version of payment, step by step, with the sample count behind each judgement.

rollout timelineruns offline
# illustrative output  (600 requests/s in total)
time   canary traffic   canary requests   error rate canary vs stable   verdict
14:00   1%               -                 -                             starts
14:05   1%               1,800             0.9% vs 0.1%                  -> over margin and over 1,000 samples ✗
14:06   0%               -                 -                             analysis failed 3 of 5 -> abort, traffic back to stable in under a minute

What you see: The rollout status after the abort, with the failed version kept for investigation.

kubectl argo rollouts get rollout paymentruns offline
# illustrative output
Name:     payment
Status:   ✖ Degraded
Message:  RolloutAborted: Rollout aborted update to revision 42: Metric "payment-vs-stable" assessed Failed
Strategy: Canary
  Step:   0/6
  SetWeight: 0     ActualWeight: 0

Why: Nobody watched a dashboard. The analysis compared two live versions on the same minute, and at 1% the harm was about 1,800 requests, not the whole fleet.

What you see now: A healthy version passes every step and ends at 100% in about 30 minutes.

rollout timelineruns offline
# illustrative output
14:00   1%   ✓   14:05  10%  ✓   14:15  50%  ✓   14:25  100%  ✓ done

Land it The canary compares two versions live on the same metrics a customer would care about, and the rollback is a decision the pipeline makes so no one has to.

Likely follow-ups
"What does 'statistical judgement' mean concretely — how many samples, what margin?"

It means the analysis asks whether the difference between canary and stable is bigger than random variation would produce.

The simplest version I use is a margin with a sample floor. It fails if the canary's error rate exceeds the stable's by more than 0.5 percentage points and the canary has seen at least 1,000 requests in the window.

At 1,000 requests the standard error on a 1% rate is about 0.3 points, so a 0.5-point margin is roughly a two-sigma test.

Kayenta does this properly with a Mann-Whitney test comparing the distributions of per-minute values, which handles latency better than a threshold does.

Argo Rollouts' analysis is simpler. It uses a PromQL expression with a success condition and a failure limit such as "fail if the condition is false in 3 of 5 measurements".

I set the measurement interval to a minute and require consecutive failures to avoid reacting to one bad scrape.

The sample floor matters more than the test: with fifty requests no test is meaningful.

"How does the metric know which version it came from?"

The deployment injects the version as an environment variable, APP_VERSION from the image tag.

The service's metrics registry adds it as a common tag on every meter. In Spring Boot that is management.metrics.tags.version=${APP_VERSION}, and every series from that pod then carries version="1.42.0".

The mesh provides the same distinction from outside. Istio's request metrics carry the destination workload and its version label from the pod's version label.

The analysis can then query the canary's error rate from the proxy's point of view without relying on the application.

I use both, because the mesh view catches a version that crashes before it emits metrics.

The one thing to avoid is a commit hash as the version tag, which creates a new series set per commit; the semantic version or the rollout's revision number is bounded.

"What does the rollback do about the Kafka consumers in the canary pods?"

It has to treat them as a separate concern, because a traffic split does not apply to consumers.

partition share is not traffic shareruns offline
# illustrative output
payment consumers: 5 pods, 20 partitions, 4 each        1 canary pod joins -> 6 pods
group of 6: 20 / 6 -> canary gets 3 or 4 partitions = 15-20% of messages   (HTTP weight was 1%) ✗

A canary pod that joins the consumer group takes its share of partitions immediately, and 1% of HTTP traffic can be 20% of the messages. Two approaches.

The safer one is to disable consumers in canary pods. The rollout sets an environment variable that stops the listener containers from starting.

The canary then judges the HTTP path. The consumer path is judged separately by a canary of the consumer deployment, which is split by partition share rather than by traffic percentage.

The alternative, if the consumer path must be in the canary, is to accept the partition share. The analysis then watches the consumer's error rate and lag by version.

The rollback stops the canary pods, which triggers a rebalance back to stable. With static membership the rebalance is quick.

Either way the consumer logic must be idempotent, because a rollback mid-batch redelivers.

"What would you cut under time pressure?"

The four traffic steps and the business metrics, temporarily.

A single step is most of the value: 10% for ten minutes judged on error rate and p99 versus stable, then 100%, with automatic rollback.

It can be set up in Argo Rollouts in an afternoon if the mesh or ingress supports weighted routing.

I keep the comparison against stable rather than an absolute threshold, because that is the part that makes the analysis meaningful.

I defer the cohort routing, the business metrics, and the longer steps.

I write down that until the business metrics exist the canary will miss a login bug like the one in the previous question.

The hotfix path I would build on day one, because without it the first incident during a rollout leads someone to disable the canary entirely, and it never comes back.

Q107. "Rolling, blue/green, canary — what does each cost and when do you pick each?"

Reveal answer

Strong answer A rolling update replaces instances a few at a time. It is Kubernetes's default and needs no extra capacity.

It gives a gradual exposure by accident rather than by design: there is no analysis and no fast rollback, only a reverse roll.

Blue/green keeps two full environments, deploys to the idle one, and switches all traffic at once.

Rollback is a switch back in seconds. The cost is double capacity during the window and an all-or-nothing exposure, so a bug hits everyone at once.

Canary sends a small, growing slice of traffic to the new version with automated comparison and rollback.

It gives the smallest blast radius and the most confidence. It costs the tooling (traffic splitting, version-tagged metrics, an analysis step) and time per rollout.

When I pick each one:

  • Rolling: low-risk internal services, and stateful consumers where two versions running concurrently for long is itself a problem.
  • Blue/green: when I need instant rollback and the change is atomic, such as a version with a coordinated data format, a large stateful service, or a compliance-driven cutover.
  • Canary: user-facing services with enough traffic to judge on and a platform that already has a mesh or ingress that can split.

All three require backward-compatible changes, because in every one of them both versions are live at some moment.

Picture it The same bad release of the order service under all three strategies, with the share of users it reaches and how long the rollback takes. See blue/green and canary.

The setup: Four pods serve the order service. Version 2 has a bug that fails every request it handles.

rolling update settingsruns offline
strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 1            # one extra pod during the rollout
    maxUnavailable: 0      # capacity never dips

The trace: What each strategy does over time to the same four-pod service.

three timelinesruns offline
# illustrative output
ROLLING   t0 v1 v1 v1 v1 | t1 v2 v1 v1 v1 (25% fail) | t2 v2 v2 v1 v1 (50%) | t3 75% | t4 100%, then a reverse roll
BLUE/GREEN  blue: v1 v1 v1 v1 (all traffic)   green: v2 v2 v2 v2 (idle, tested)
            t1 switch: 100% of traffic -> green, every user hits the bug ✗ ; t2 switch back: seconds ✓
CANARY    t0 5% -> 25% -> 50% -> 100%, analysis at each step
            at 5% the error comparison fails -> abort, 5% of users saw the bug ✓

What you see: The cost and risk rows for the same release, side by side.

Same bad release, three strategies
QuestionRollingBlue/greenCanary
Extra capacity during the deploy1 pod4 pods (double)1 to 2 pods
Users hit before anyone judges25% to 100%, no judge100% at the switch5%, then judged
RollbackReverse roll, minutesSwitch back, secondsAutomatic, within a minute
Needs backward-compatible schemaYesYesYes

Why: All three have both versions live at some moment, so compatibility is required in all three. They differ in how much of the traffic sees the new version before something decides.

Land it Canary for confidence, blue/green for instant reversal, rolling for the rest — and none of them is safe without compatible changes.

Likely follow-ups
"What are maxSurge and maxUnavailable, and how do they change a rolling update's risk?"

They are the two knobs on a Kubernetes rolling update:

  • maxSurge is how many extra pods above the desired count may exist during the rollout.
  • maxUnavailable is how many pods below the desired count may be missing.

The defaults are 25% each.

With maxSurge: 1 and maxUnavailable: 0, the rollout adds one new pod and waits for it to be ready. Then it removes one old pod and repeats.

Capacity never dips and the exposure grows one pod at a time, which is the slowest and safest setting.

With maxUnavailable: 50%, half the pods are killed at once, which is fast and drops capacity by half.

For a service near its capacity limit, maxUnavailable: 0 is mandatory or the rollout itself causes an overload.

For a Kafka consumer, a larger surge means fewer rebalance rounds. So the knobs are where a rolling update's gradualness comes from, and the default is not always the right one.

"With blue/green, what happens to in-flight requests and database state at the switch?"

In-flight requests on blue finish on blue, because the switch changes where new connections go.

Blue keeps serving until its connections drain. The load balancer's connection draining timeout, typically 30 to 60 seconds, governs that.

Long-lived connections such as WebSockets or gRPC streams are the exception: they stay on blue until closed, so the switch must either drain them actively or accept that blue keeps a trickle of traffic for a while.

Database state is the harder part. Both colours share one database, so the schema must be compatible with both versions, exactly as in a rolling update.

If green writes data in a new format, a switch back to blue must be able to read it.

Sessions in a per-instance cache are lost at the switch unless they live in a shared store. So blue/green removes the overlap in the request path but not in the data path, and the data path is where the compatibility work is.

"Can you canary a database change?"

Not the migration itself, because a schema has one version at a time. What you canary is the code that uses the schema, after the migration has been applied in its expanded form.

The sequence is:

  1. Apply the additive migration in its own deployment step with no code change.
  2. Verify it did not lock or slow anything.
  3. Canary the code that reads the new column.

A data migration — a backfill — is canaried in a different sense: run it on a slice of rows first, verify, then the rest.

What a canary cannot judge is whether a migration was correct. Correctness of data shows up later and not in request metrics.

reconciliation checkruns offline
SELECT count(*) FROM orders WHERE amount IS DISTINCT FROM total_amount;   -- ✅ must be 0 before the contract step
-- Result (illustrative): 0

That needs a reconciliation check comparing old and new columns.

So the honest answer is that database changes are made safe by expand-and-contract and by running them separately from code deploys, and the canary covers the code around them.

"A stateful service — say a search index or a cache cluster. Which strategy?"

Blue/green at the level of the data, which is a different thing from blue/green at the level of pods.

For a search index, the new version builds a new index alongside the old, is validated against it, and the alias switches — the index is the green environment.

For a cache cluster, a rolling upgrade of nodes with the cluster's own replication keeps the data available, which is what the cluster software is built for, and the application-level strategy is irrelevant.

For a stateful service with an on-disk format that changes, the choice is forced: the new version must read the old format.

A rolling update is fine if each node upgrades its own data on start. Otherwise the migration is a one-way step with a backup taken first.

What I do not do is a canary in the sense of a traffic split, because a stateful service's correctness is not visible in a traffic slice — a corrupt index serves fast, wrong answers.

Q108 · Scenario. "Every rolling deploy of the inventory consumer causes consumer lag to spike to 500,000 and take twenty minutes to recover. There are 24 pods and 24 partitions. Why, and what do you change?"

Reveal answer

Strong answer With one partition per pod and a rolling update replacing pods one at a time, every pod stop and every pod start triggers a consumer-group rebalance. That is 48 rebalances per deploy.

Under the classic protocol each rebalance pauses the whole group while partitions are reassigned.

Every pause loses seconds of consumption across all 24 partitions. The lag accumulates faster than the group can catch up.

Evidence to collect:

  • The rebalance count metric during a deploy.
  • The pause per rebalance.
  • Which assignor and group protocol the consumer uses.

Causes, most likely first:

  1. Eager protocol: all members drop all partitions on each change.
  2. No static membership: a restarted pod is treated as a new member rather than the same one returning.
  3. Rollout shape: maxSurge and maxUnavailable change membership twice per pod.

Fixes:

  1. Static membership: set group.instance.id from the pod's stable name, so a pod restart within session.timeout.ms keeps its partitions with no rebalance at all.
  2. Incremental protocol: use the cooperative-sticky assignor or, on Kafka 4.x, the new consumer protocol (KIP-848). It reassigns incrementally without pausing the group.
  3. Larger batches: deploy in larger batches so fewer rebalances happen.
  4. Stable identities: use a StatefulSet so the mapping holds.

Prevention: a deploy in staging measured for lag as a gate, and over-provisioned partitions so the group is not at a one-to-one edge.

Picture it The lag arithmetic of 48 pauses, the group state before and after static membership, and the log lines of one rebalance.

The trace: One deploy of the 24-pod inventory consumer under the classic protocol, as numbers.

lag arithmeticruns offline
# illustrative output
rebalances per deploy        24 stops + 24 starts            = 48
pause per rebalance          about 5 s, whole group stopped
total stoppage               48 x 5 s                        = 240 s
messages arriving meanwhile  240 s x 2,000 / s               = 480,000  -> lag ~ 500,000
headroom                     consumer at 80% of capacity -> spare 20% = 400 / s
recovery                     480,000 / 400                   = 1,200 s = 20 minutes

What you see: The group description during the deploy, and the log lines each rebalance leaves.

kafka-consumer-groups --describe --group inventoryruns offline
# illustrative output
GROUP      TOPIC       PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG      CONSUMER-ID
inventory  stock-events   0       1,204,331       1,204,331       0        inventory-consumer-3f9a-...
inventory  stock-events   1       1,198,002       1,218,114       20,112   -     (rebalancing)  ✗
inventory  stock-events   2       1,200,870       1,221,402       20,532   -     (rebalancing)  ✗
consumer log, one rebalanceruns offline
# illustrative output
(Re-)joining group
Revoke previously assigned partitions stock-events-1     <- eager: ALL partitions are revoked
Adding newly assigned partitions stock-events-1          <- consumption resumes only now

The fix: Stable member ids, a session timeout longer than a restart, and an incremental protocol.

consumer settingsruns offline
spring:
  kafka:
    consumer:
      properties:
        group.instance.id: ${HOSTNAME}          # ✅ FIX: inventory-consumer-0 in a StatefulSet
        session.timeout.ms: 90000               # ✅ FIX: longer than a pod restart
        partition.assignment.strategy: org.apache.kafka.clients.consumer.CooperativeStickyAssignor
        # on Kafka 4.x with the new protocol: group.protocol: consumer instead of the assignor

What you see now: Rolling the same 24 pods: each restart returns inside the session timeout, so the group does not rebalance.

lag arithmeticruns offline
# illustrative output
rebalances per deploy        0   (each pod back as the same member inside 90 s)
partitions paused            only the one whose pod is restarting, about 20-30 s each
peak lag                     small, recovered in a minute ✓

Land it Static membership and an incremental protocol turn a rolling deploy from 48 group pauses into none, and that is a configuration change, not an architecture change.

Likely follow-ups
"Show me the configuration for static membership and explain the timeout interaction."

In Spring Kafka, spring.kafka.consumer.properties.group.instance.id=${HOSTNAME} gives each pod a stable member id from its pod name.

The name is stable in a StatefulSet. In a Deployment it is stable enough for a restart of the same pod but not across a replacement.

That is why I use a StatefulSet for consumers that want static membership: inventory-consumer-0 is the same member forever.

The interaction is with session.timeout.ms. The broker holds a static member's partitions for that long after it disconnects, waiting for it to return, and only rebalances if it does not.

So the session timeout must be longer than a pod's restart time. I set 60 to 90 seconds, up from the default 45, and the rollout's pod replacement must complete inside it.

If the pod returns in time, there is no rebalance. If not, there is one rebalance, and a second when it finally joins.

The cost of a long session timeout is that a truly dead pod's partitions sit idle for that long before reassignment.

"What is the difference between the cooperative-sticky assignor and KIP-848, and which do you pick as of Aug 2026?"

The cooperative-sticky assignor is a client-side protocol. The group still goes through a rebalance, but in two rounds, and members only give up the partitions that actually move.

The rest keep consuming throughout.

It is set with partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor and needs a two-step migration from the eager assignor.

KIP-848 is the new consumer group protocol, shipped as production-ready in Kafka 4.0. It moves assignment to the broker.

The coordinator computes the assignment and tells each member incrementally. There is no group-wide synchronisation barrier at all, and the member configuration is just group.protocol=consumer.

As of Aug 2026, on a 4.x cluster with clients on 4.x, I pick KIP-848, because it is simpler to configure and rebalances are both faster and quieter.

On a 3.x cluster, cooperative-sticky with static membership is the combination. Either one fixes this incident; the new protocol also removes the assignor configuration class of mistakes.

Either one fixes this incident; the new protocol also removes the assignor configuration class of mistakes.

"Where does the 500,000 lag come from — twenty minutes to recover seems long for a few seconds of pause."

From the multiplication.

Each rebalance under the eager protocol stops all 24 partitions for the rebalance duration. With a 24-member group and a default max.poll.interval.ms that can be several seconds.

The coordinator waits for every member to rejoin, up to the poll interval if a member is mid-batch.

Forty-eight rebalances at five seconds each is four minutes of total stoppage across all partitions.

At a production rate of, say, 2,000 messages a second, four minutes of stoppage is 480,000 messages.

Recovery is slow because the consumer's headroom is small. If it normally runs at 80% of its capacity, it clears the backlog at only 20% of its rate, 400 a second.

480,000 at 400 a second is twenty minutes.

That arithmetic is also the argument for keeping consumer headroom at 50% rather than 20%, because recovery time from any pause is proportional to the inverse of the headroom.

"The fix didn't work — static membership is on and the lag spike is smaller but still happens. Why?"

Because the pod names are not stable, so the broker sees new members.

In a Deployment, a rolling update creates pods with new random suffixes. So group.instance.id from the hostname is a new id each time, and static membership does nothing.

instance ids across a Deployment rolloutruns offline
# illustrative output
before rollout:  group.instance.id = inventory-consumer-7d9f-abcde, ...-fghij
after rollout:   group.instance.id = inventory-consumer-5c4b-klmno, ...-pqrst    ✗ all new members, old ones wait out the session timeout
StatefulSet:     inventory-consumer-0 ... inventory-consumer-23                 ✓ same ids after a restart

The old member's partitions are held until its session expires and then reassigned, which is actually worse than before.

The check is the consumer group description: members whose instance ids do not match the previous set. The fix is the StatefulSet or an explicit ordinal-based id.

The second cause is the session timeout. If a pod takes 70 seconds to restart and the session timeout is 45, the broker gives up and rebalances anyway.

The third cause is that the consumer is also in a second group, such as a health check or a metrics exporter creating a consumer per pod. It rebalances independently and shows up as a smaller spike.

I would look at the rebalance metric per group to separate them.

I would look at the rebalance metric per group to separate them.

Q109. "Feature flags: how do they separate deploy from release, and what is flag debt?"

Reveal answer

Strong answer A feature flag is a runtime switch that decides whether a code path is active. It is evaluated per request from a configuration source that can change without a deploy.

It separates deploying code — putting it on the servers — from releasing it — letting users see it.

Code ships dark behind a flag as part of the normal continuous deployment flow. Then:

  1. The flag is turned on for internal users.
  2. Then for 1% of customers.
  3. Then for everyone. This is the same cohort logic as a canary, but at the level of a feature rather than a version.
  4. Turning it off is a configuration change that takes seconds, which is the fastest rollback there is.

That decoupling lets many teams merge and deploy continuously while product decides release timing.

Flag debt is what accumulates when flags are never removed. There are hundreds of switches, each a branch in the code, whose combinations nobody has tested.

A config change that flips an old flag causes an incident two years after its feature launched.

The disciplines that prevent it:

  • Every flag has an owner and an expiry date.
  • Flags are removed within a sprint of reaching 100%.
  • A report lists stale flags.
  • Permanent switches, such as kill switches for dependencies and operational toggles, are a separate, small, documented category.

Tooling as of 2026 spans the OpenFeature standard with providers such as LaunchDarkly, Unleash, and Flagsmith.

Picture it The flag as one decision point in code, the release timeline that never redeploys, and the flag report that exposes debt.

The setup: One branch at the top of the checkout flow, with a safe default.

flag evaluationruns offline
boolean useNewCheckout = client.getBooleanValue(
        "new-checkout", false, evaluationContext);        // ✅ FIX: default false = yesterday's behaviour
return useNewCheckout ? newCheckout.place(cart) : legacyCheckout.place(cart);   // one decision point

The trace: Deploy and release are separate events. The code is live from 09:00 and users see it from 10:00.

flag timelineruns offline
# illustrative output
09:00  deploy v1.50 (flag new-checkout = off)      users see: old checkout
10:00  flag -> internal users                      users see: old, staff see new
10:15  flag -> 1%                                  metrics watched
10:30  flag -> 10%        error rate jumps to 3%   ✗
10:31  flag -> 0%         (config change, no deploy) recovered in seconds ✓

What you see: The stale flag report is where flag debt becomes visible.

flag reportruns offline
# illustrative output
flag                 owner       state    age      note
new-checkout         payments    100%     14 days  remove branch this sprint
promo-banner-2024    growth      100%     610 days STALE ✗ nobody owns the legacy path
payment-kill-switch  platform    off      permanent (kill switch category) ✓

Why: A flag at 100% is just an if statement with no purpose, and its untested combinations with other flags are the risk.

Land it A flag is a rollback that takes seconds and a branch that must be deleted, and a team that does the first without the second is building the next incident.

Likely follow-ups
"How is a flag evaluated per request without a network call per request?"

The flag service pushes rules to the application, and the application evaluates locally.

The SDK (LaunchDarkly's, Unleash's, or an OpenFeature provider) opens a streaming connection or polls every few seconds. It keeps the full rule set in memory.

It evaluates a flag for a given context in microseconds with no network call: client.getBooleanValue("new-checkout", false, evaluationContext). The context carries the user id and attributes for cohort rules.

A rule change propagates in seconds.

If the flag service is unreachable at startup, the SDK starts with the last cached rule set from disk or the defaults in code.

So the flag service is not an availability dependency, which is the same lesson as the config server question.

The default value in the call is the fallback and it must be the safe behaviour, usually "off". I never evaluate a flag by calling an HTTP endpoint on the request path.

"How do you test code with flags without testing every combination?"

By testing each flag's two states in isolation and the combination that will actually ship.

For a flag under active development the unit tests set the flag on and off explicitly through an in-memory provider and cover both paths.

The integration suite runs with the production default — the state that is or will be live — and a nightly run flips the flags scheduled for release next, so the shipping combination is exercised.

Testing all combinations is impossible past a handful of flags. That is the practical reason flag debt is dangerous: it is untested state space.

Two structural rules limit it.

A flag is a single decision point, not scattered if checks. The branch happens once at the top of a flow and selects an implementation.

And flags do not interact by design. If two flags must be on together, they are one flag.

The report of flags older than ninety days is what keeps the combination count small.

"A flag flip caused an outage. What was wrong, and how should flag changes be governed?"

A flag flip is a deploy with no pipeline, and it needs the same protections.

The likely failure is a flag turned to 100% in one step, which is the equivalent of a deploy with no canary.

Governance: flag changes in production go through the same percentage steps as a rollout, 1%, 10%, 50%, 100%, with the same metrics watched.

The flag tool records who changed what and when, so the change shows as a marker on dashboards.

Kill switches, which are meant to be flipped fast during incidents, are the exception and are tested regularly so they are known to work. Every flag change is announced in the team's channel automatically.

And the fallback direction is always safe: the code path that runs when the flag is off is the one that ran yesterday.

What I would add after this incident is that a flag reaching 100% is treated as the moment to schedule its removal, because a flag that stays after 100% is now a latent switch with no reason to exist.

"What does the OpenFeature standard give you, and why bother?"

It gives a vendor-neutral API for evaluating flags: the Client, the evaluation context, hooks, and a provider interface that each vendor implements.

The application code calls OpenFeature. The provider translates to LaunchDarkly, Unleash, Flagsmith, a file, or an in-memory map for tests.

The reason to bother is the build-versus-buy answer from later in this drill: a flag service is a commodity, and the standard makes it swappable, so a pricing change or an outage at the vendor is a configuration change rather than a rewrite across forty services.

It also gives a uniform test provider, so every service tests flags the same way, and hooks let the platform add tracing attributes and metrics to every evaluation without each team doing it.

The cost is a thin extra layer and occasionally a vendor feature that the standard does not expose. As of Aug 2026 the Java SDK is stable and the main vendors ship providers, so there is little reason to code against a vendor SDK directly.

Q110 · Design. "Design configuration and secrets management for thirty services on Kubernetes, including rotation without downtime."

Reveal answer

Strong answer Three requirements drive the design:

  • Configuration differs per environment but the image is identical.
  • Secrets never appear in git, images, or logs.
  • A leaked database password can be rotated in minutes without restarting anything.

The design has two tracks.

Configuration track: non-secret settings live in git as per-environment files. The deployment pipeline (GitOps with Argo CD) applies them as Kubernetes ConfigMaps.

They are injected as environment variables or mounted files and read by Spring Boot's normal property sources. Runtime-changeable settings, such as timeouts and feature flags, come from a flag service, not from redeploying ConfigMaps.

Secrets track: the source of truth is a secrets manager (HashiCorp Vault or the cloud provider's).

The External Secrets Operator syncs them into Kubernetes Secrets. These are mounted as files, never as environment variables, because files can be updated in place and environment variables cannot.

Services read secrets from the mounted files and re-read on change. Spring Cloud Kubernetes or a small file watcher handles the reload. Rotation is then:

  1. Write the new secret to the manager.
  2. The operator syncs it within a minute.
  3. The file updates.
  4. The service picks it up.

For databases, dynamic credentials from Vault's database engine give each pod its own short-lived user, so rotation is automatic and revocation is per pod.

Access to the manager uses the pod's workload identity (a projected service-account token), so there is no bootstrap secret.

Trade-offs: several operators to run. What I would not do is put secrets in Helm values or environment variables in a Deployment manifest, which is where most leaked secrets actually live.

Picture it The path of a password from the manager to the process, the rotation minute by minute with the pool state, and why a file survives a rotation and an environment variable does not. See externalized config.

Make the invisible visible: The secret travels through four hops and the application only ever sees a file.

secret pathruns offline
Vault / secrets manager  --(External Secrets Operator, refresh ~1 min)-->  Kubernetes Secret
Kubernetes Secret        --(kubelet, updates the volume in place)------->  /etc/secrets/db-password
/etc/secrets/db-password --(file watcher in the service)---------------->  HikariCP credential
pod identity: projected service-account token -> Vault role "order-service"   (no bootstrap secret)

The trace: A zero-downtime rotation: both passwords are valid until every pod has moved.

rotation timelineruns offline
# illustrative output
time   event                                           valid passwords   pods on new
00:00  new password created, old still works             old + new         0 / 12
00:01  manager updated, operator syncs the Secret        old + new         0 / 12
00:03  kubelet updates the mounted file                  old + new         0 / 12
00:04  watchers reload, new connections use new          old + new         12 / 12 ✓
00:05  metric credential_version = 2 on all pods         old + new         12 / 12
00:05  old password revoked                              new               12 / 12 ✓  (roll back before this: keep old valid)

What you see: The same secret as an inline environment variable and as a secret reference. Only the first prints the value.

kubectl describe pod, environment sectionruns offline
# illustrative output
Environment:
  DB_PASSWORD:  s3cr3t-inline        <- ❌ TRAP: literal value in the manifest, visible here and in git
  DB_USER:      <set to the key 'user' in secret 'order-db'>   Optional: false
# a file in /etc/secrets is not listed at all, and it can change without a restart ✅

The fix: Mount the Secret as a directory and import it as configuration.

pod spec and Spring importruns offline
volumes:
- name: secrets
  secret: {secretName: order-db}            # ✅ FIX: a file, updated in place by the kubelet
containers:
- name: order
  volumeMounts: [{name: secrets, mountPath: /etc/secrets, readOnly: true}]
# application.yml
spring:
  config:
    import: "configtree:/etc/secrets/"

Land it Config in git, secrets in a manager synced to mounted files, and workload identity to fetch them — that is a system where rotation is a routine, not an outage.

Likely follow-ups
"Walk me through rotating the database password with zero downtime, step by step."

The key is that two passwords are valid at once. Step one: create the new credential while the old one still works.

In PostgreSQL that is either a second role with the same grants or, if the driver supports it, the database's dual-password feature.

Step two: write the new password to the secrets manager.

The External Secrets Operator syncs the Kubernetes Secret within its refresh interval, typically a minute. The kubelet updates the mounted file within its own sync period, usually under two minutes.

Step three: the application's file watcher notices the change and rebuilds the connection pool's credential.

With HikariCP that means getHikariConfigMXBean().setPassword() plus a soft eviction, so new connections use the new password while existing connections keep working.

Step four: after every pod reports the new credential in use — a metric of the credential version — revoke the old password.

Total elapsed time about five minutes, no restart, and the rollback at any point is to keep the old password valid a while longer.

"Why files rather than environment variables? Many teams use env vars for secrets."

Three reasons:

  1. Rotation: environment variables are fixed at process start, so rotation requires a restart, which turns every rotation into a rolling deploy of thirty services. Files mounted from a Secret are updated in place by the kubelet, so the process can re-read them.
  2. Leaks: environment variables appear in kubectl describe pod, in crash dumps, in the /proc/<pid>/environ of any process that can read it, and in child processes. Frameworks also log their environment on startup. Files are readable only by the container's user.
  3. Habit: environment variables in a Deployment manifest are usually populated from the Secret by name, which is fine. The habit slides into putting values inline in Helm values files, which end up in git.

Spring Boot reads a mounted directory as configuration with spring.config.import=configtree:/etc/secrets/, so files are no harder to consume. The one place env vars are acceptable is a non-secret setting such as the environment name.

"What does workload identity actually look like — how does a pod prove to Vault that it is the order service?"

Through the Kubernetes service account token, which is a JWT the kubelet projects into the pod and the cluster's API server signs.

Its claims name the namespace and service account and, for projected tokens, carry a short expiry and a specific audience.

The pod sends that token to Vault's Kubernetes auth method. Vault then does three things:

  1. It validates the token against the cluster's token review API or its public keys.
  2. It checks that the namespace and service account match a role, such as order-service in namespace orders.
  3. It returns a short-lived Vault token with the policies for that role.

The Vault Agent or the External Secrets Operator does this on the pod's behalf, so the application never sees a Vault token.

The important property is that there is no secret to bootstrap: the identity comes from the platform's own signing key, which the pod cannot forge.

The same pattern works for cloud providers — IRSA on AWS, Workload Identity on GCP — where the projected token is exchanged for a cloud credential.

"The secrets manager is down. What happens to the platform?"

Nothing, if the design is right, and I would test that with a game day. Running pods have their secrets in mounted files already.

They do not talk to the manager at all. Only the operator does.

The operator fails to sync and raises an alert, but existing Secrets are untouched. New pods start from the existing Kubernetes Secret, which is stored in etcd, so scaling and restarts work.

The one thing that stops is rotation, and a rotation in progress could be caught half-done, which is why the old credential stays valid until the new one is confirmed everywhere.

Dynamic database credentials are the exception. If each pod gets a short-lived user from Vault's database engine, a pod that starts during the outage cannot get one.

A lease that expires cannot renew.

So for dynamic credentials I set a lease long enough to ride out a reasonable outage — hours, not minutes — and I accept that a very long outage eventually blocks new pods, which is the trade for per-pod revocation.

"What would you cut under time pressure?"

Dynamic database credentials and the runtime reload, not the manager or the mounting.

A first version has the manager as the source of truth, the operator syncing to Kubernetes Secrets, secrets mounted as files, and workload identity for the operator — that gives "never in git, never in the image" and a single place to rotate.

Rotation in the first version is a rolling restart after the Secret updates, which is a minute of pods cycling and is acceptable for a quarterly rotation. Runtime reload comes second, when a rotation needs to be an emergency response rather than a scheduled one.

Dynamic per-pod credentials come third, because they need the database engine configured in Vault and a lease-renewal path in every service.

What I would not cut is the rule that Helm values and Deployment manifests contain no secret values, enforced by a pre-commit scan such as gitleaks, because that is where the leaks actually happen.

Q111. "mTLS, OAuth 2.0 with OpenID Connect, and zero trust — how do the three fit together in a service platform? What does each one prove?"

Reveal answer

Strong answer They answer three different questions.

  • mTLS: which workload is on each end of the connection.
  • OAuth 2.0 with OpenID Connect: which user, or which client application, the request is acting for, and what it may do.
  • Zero trust: the policy that makes every hop check both answers instead of trusting the network.

Mutual TLS proves which workload is on each end of a connection. Both sides present certificates issued by the platform's certificate authority.

Payment knows the connection really comes from the order service and not from a compromised pod pretending to be it. The traffic is also encrypted.

A service mesh issues and rotates these certificates automatically, which is what makes mTLS practical at scale.

OAuth 2.0 is the protocol for issuing access tokens, and OpenID Connect adds identity on top.

Together they prove which user (or which client application) a request is acting for, and what they are permitted to do, through a signed token that travels with the request.

Zero trust is the policy that ties them together: no request is trusted because of where it came from on the network; every hop verifies the calling workload (mTLS) and the acting user (the token) and makes its own authorisation decision.

In practice:

  1. The gateway validates the user's token.
  2. The order service calls payment over mTLS and forwards the user's token, or a short-lived token exchanged for this call.
  3. Payment checks both the workload identity (only order and refund services may call charge) and the user's scope (this user may pay for this order).

None of the three replaces another — mTLS without tokens knows the caller but not the user; tokens without mTLS can be replayed by any workload that obtains one.

Picture it One charge call across four lanes with what each hop verifies, then four attacks and which control stops each. The mesh side is sidecar and mesh.

The trace: The checkout call from the browser to payment. Each row names the check made at that hop.

sequence lanesruns offline
step  lane                       check made                                          result
1     Browser -> Gateway         access token: signature, expiry, issuer, audience   ✓
2     Gateway -> Order           mTLS: Order is spiffe://.../sa/order-service        ✓
3     Order -> Payment           mTLS: caller is order-service, allowed to call charge  ✓
4     Payment                    token: scope "pay" for this order, audience payment    ✓
5     Payment -> Order           201 Created

What you see: Four attempts on the same endpoint, and what stops each one.

Attempts against payment /charge
AttemptmTLS onlyTokens onlyBoth, every hop
Compromised inventory pod calls /chargeFails: not on the allowed caller listWorks if it holds a stolen user tokenFails: workload not allowed
Allowed order pod, no user tokenWorks: nobody asks who the user isFails: 401Fails: 401
Allowed order pod, token with scope "read" onlyWorksFails: 403Fails: 403
Plain HTTP from inside the clusterFails: no certificateWorks, and the token is readable on the wireFails: no certificate

Make the invisible visible: Why services validate access tokens and never ID tokens: the audience claim differs.

decoded claims (shortened)runs offline
# illustrative output
ID token      aud=web-app-client-id   sub=u-1042  email=ana@example.com   (for the front end to read)
access token  aud=payment-api         sub=u-1042  scope="pay"  exp=...    (the one payment validates ✓)

Why: Each control answers a different question, so removing any one leaves one of the four rows open.

Land it mTLS proves the machine, the token proves the person, and zero trust means every hop checks both instead of trusting the network.

Likely follow-ups
"What is a SPIFFE ID, and how does the mesh rotate certificates without anyone noticing?"

A SPIFFE ID is a URI that names a workload, such as spiffe://cluster.local/ns/orders/sa/order-service.

It is embedded in the certificate the mesh issues to that workload as a subject alternative name.

It is derived from the pod's namespace and service account, so it is the same identity the workload-identity question used, expressed as a certificate.

Rotation works because the proxy, not the application, holds the certificate:

  1. The sidecar requests a certificate from the mesh's certificate authority using the pod's service account token.
  2. It gets one valid for 24 hours by default in Istio.
  3. It requests a new one at roughly half its lifetime.

Connections established with the old certificate stay valid until they close. New connections use the new one.

The application sees plain HTTP to and from its local proxy and is unaware any of this happens.

The failure mode is the CA being unreachable for longer than a certificate's lifetime, which is why the lifetime is hours rather than minutes and the CA is highly available.

"What is the difference between an access token and an ID token, and which one do services validate?"

The ID token is OpenID Connect's proof of who logged in. It is a JWT addressed to the client application, so the audience is the app's client id.

It carries identity claims such as subject, name, and email, and it is meant for the app to read, not to forward.

The access token is OAuth's authorisation credential. It is addressed to a resource server, so the audience is the API, and it carries scopes and often the subject.

It is what the client sends to the API. Services validate access tokens, never ID tokens. A service that accepts an ID token as authorisation is accepting a credential that was never meant for it and has no scopes.

Spring Security's resource server checks the access token's signature against the issuer's JWKS, its expiry, its issuer, and its audience.

I always set the audience check explicitly, because a token for a different API with a valid signature would otherwise be accepted. The ID token stays in the front end.

"Does mTLS inside the mesh mean you no longer need TLS from the application?"

Between services inside the mesh, yes. The sidecars encrypt the hop, and the application speaks plain HTTP to its local proxy over the pod's loopback interface, which is not observable from outside the pod.

That is the operational win: no certificate management in thirty codebases.

The exceptions are the edges:

  • Traffic from the internet to the gateway terminates TLS at the gateway or the load balancer with a public certificate.
  • Traffic to anything outside the mesh, such as a managed database, a third-party API, or a legacy VM, needs TLS from the client, because there is no sidecar on the far end. The mesh can originate TLS for egress, but the database driver usually does its own with sslmode=verify-full.

And with ambient mode, the per-node proxy handles encryption between nodes, and traffic between pods on the same node is still protected, but I would verify that in the specific mesh version rather than assume it.

"What is a token exchange and why does forwarding the user's token to the next service not suffice?"

Forwarding the user's original token works but gives every downstream service a token that is valid for every API the user could call.

If the payment service is compromised, the attacker holds tokens that work against the account service, the order service, and anything else in the token's audience.

If the payment service is compromised, the attacker holds tokens that work against the account service, the order service, and anything else in the token's audience.

A token exchange, RFC 8693, lets the order service present the user's token to the identity provider. It receives a new token whose audience is only the payment service and whose scope is only what this call needs, still carrying the user's subject.

The downstream then validates an audience that names it specifically.

The downstream then validates an audience that names it specifically.

The cost is one call to the identity provider per hop. It is mitigated by caching exchanged tokens for their short lifetime and by doing the exchange only at the boundaries that matter, such as calls into payment or identity.

For hops between two low-risk services I forward the original token and accept the wider audience, and I write that decision down.

Q112 · Scenario. "A security audit found that the refund endpoint on the payment service accepts any request from inside the cluster, with no authentication. The team says it is 'internal only'. Assess the risk and fix it in stages."

Reveal answer

Strong answer The risk is real and the phrase "internal only" is the vulnerability.

Evidence to gather:

  • Reach: which workloads can reach the payment service's network (with default Kubernetes networking, every pod in the cluster).
  • Untrusted code: whether any pod runs third-party or user-supplied code.
  • Caller check: whether the refund endpoint validates the caller in any way.

The threat: a compromised pod anywhere can issue refunds to arbitrary accounts, and the audit log cannot say who did it. Typical ways in:

  • a vulnerable image;
  • a server-side request forgery in a web-facing service;
  • a stolen developer credential.

Fix in stages, fastest first.

  1. Stage one, this week: a Kubernetes NetworkPolicy allowing ingress to the payment service only from the namespaces and labels of its known callers. It cuts the blast radius without code changes.
  2. Stage two: enforce mTLS through the mesh with an authorisation policy naming the caller identities allowed to reach the refund path, so the call must come from the order or support service's identity.
  3. Stage three: require a token on the refund call carrying the acting user and a refund scope, validated by Spring Security's resource-server support. The audit log then records who requested each refund, and support agents' permissions are checked per request.
  4. Stage four: alerting on refund volume and on any rejected call to the endpoint.

Prevention: a platform default that internal endpoints require workload identity, so "internal" means "authenticated as a known service", not "on the network".

Picture it A hostile pod calling the refund endpoint of the order / payment platform, and who can still do that after each of the four stages (the mesh stage uses the sidecar and mesh block).

The setup: An image-resizer pod with a known vulnerability, unrelated to refunds, calls the payment service directly.

consoleruns offline
# illustrative output
$ kubectl exec image-resizer-6f7d -- curl -s -o /dev/null -w "%{http_code}\n" \
    -X POST http://payment:8080/refunds -d '{"orderId":"o-1001","amount":49.00}'
200

Make the invisible visible: Draw who can reach the endpoint. The blast radius is every pod that shares the cluster network.

topology and blast radiusruns offline
# illustrative output
 web-bff   order   support-ui   image-resizer (CVE)   batch-recon
    |        |         |               |                  |
    +--------+----+----+---------------+------------------+
                  v
        payment:8080  POST /refunds      (no caller check)

 stage 0 blast radius: all 212 pods on the cluster network
 -> any one compromised pod can issue refunds

The trace: The same two probes, a hostile pod and the order service without a token, repeated after every stage.

Who can call POST /refunds after each stage (illustrative numbers)
StagePods that can reach itHostile image-resizer podOrder service, no tokenAudit log names
0 now212Works: 200Works: 200source IP only
1 NetworkPolicy2 workloadsFails: connection times outWorks: 200source IP only
2 mesh policy2 identitiesFails: 403 RBAC: access deniedWorks: 200workload identity
3 token required2 identities with scopeFails: 403Fails: 401workload and user

What you see: At stage 0 the audit line cannot name an actor, which is the finding the audit made.

payment audit logruns offline
# illustrative output
payment audit: POST /refunds orderId=o-1001 amount=49.00 actor=? source=10.2.4.17 status=200

Why: Nothing in the request proves who the caller is: the only gate is network reachability, and the default network is open to every pod.

The fix: The four stages above, fastest first. Stages one and two are shown as YAML in the follow-ups below.

What you see now: The same refund call from the hostile pod after each stage, and the audit line after stage three.

consoleruns offline
# illustrative output
stage 1 (NetworkPolicy):   curl: (28) Connection timed out      http_code 000
stage 2 (mesh policy):     HTTP 403   body: RBAC: access denied
stage 3 (order, no token): HTTP 401
payment audit: POST /refunds orderId=o-1001 actor=user:agent-17 workload=order-service status=200
Symptom, root cause, action
SymptomRoot causeAction
Refund works from a pod that should never call itNetwork is open by defaultNetworkPolicy allowing only known callers
Policy applied but a test pod still gets 200The CNI does not enforce NetworkPolicyUse a CNI that does (Calico, Cilium) and test with a pod that must be blocked
Call allowed but the audit log has no personNo user token on the callRequire a scoped token, validated by the resource server
Mesh policy breaks a job nobody listedUndocumented callerRun action AUDIT first, enforce when the log is quiet

Land it The network is not a security boundary, and a refund endpoint that trusts it is one compromised pod away from a very bad quarter.

Likely follow-ups
"Show me the NetworkPolicy for stage one and what it does not protect against."

The policy selects the payment pods and allows ingress only from labelled callers.

In outline: kind: NetworkPolicy, spec.podSelector.matchLabels.app: payment, policyTypes: [Ingress], and an ingress rule with from entries of namespaceSelector for the orders namespace combined with podSelector for app: order-service, and a second entry for the support namespace and pod, both on port 8080.

payment-network-policy.yamlruns offline
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: payment-allow-callers
  namespace: payments
spec:
  podSelector:
    matchLabels:
      app: payment
  policyTypes: [Ingress]        # selected pods now deny everything not listed
  ingress:
    - from:
        - namespaceSelector:    # namespace AND pod label in one entry
            matchLabels:
              kubernetes.io/metadata.name: orders
          podSelector:
            matchLabels:
              app: order-service
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: support
          podSelector:
            matchLabels:
              app: support-ui
      ports:
        - protocol: TCP
          port: 8080

Everything not listed is denied, because a pod selected by any policy denies by default.

What it does not protect against:

  • a compromised pod that already has the right labels, because labels are not identity;
  • anyone with permission to create pods in the orders namespace, who can label their pod app: order-service;
  • a node-level compromise;
  • traffic that does not traverse the CNI, which is rare but exists with host networking.

It also needs a CNI that enforces policies — Calico or Cilium do, some default network plugins silently ignore them, which is the first thing I would verify with a test pod that should be blocked.

"What does the mesh authorisation policy look like in stage two, and how do you avoid breaking a caller you forgot?"

In Istio it is an AuthorizationPolicy selecting the payment workload with an ALLOW rule whose from.source.principals lists the SPIFFE identities of the order and support service accounts and whose to.operation matches POST on /refunds*, plus a default deny for the workload.

payment-authz.yamlruns offline
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
  name: payment-refunds
  namespace: payments
spec:
  selector:
    matchLabels:
      app: payment
  action: ALLOW                 # once an ALLOW policy selects the workload, unmatched requests are denied
  rules:
    - from:
        - source:
            principals:         # SPIFFE identities from the mTLS certificate, not labels
              - cluster.local/ns/orders/sa/order-service
              - cluster.local/ns/support/sa/support-ui
      to:
        - operation:
            methods: ["POST"]
            paths: ["/refunds*"]
# first run it with action: AUDIT and read the log for forgotten callers

Principals come from the mTLS certificate, so they cannot be spoofed by a label.

To avoid breaking a forgotten caller, I run the policy in audit mode first: Istio's action: AUDIT logs what would have been denied without denying it, and a week of those logs is the list of every real caller — usually one or two that nobody documented, such as a reconciliation job.

Only after the log is quiet do I switch to enforce. I also keep mTLS in permissive mode until every caller has a sidecar, because strict mode blocks plaintext callers outright, and a legacy job without a sidecar is a common surprise.

"Stage three requires a user token on refunds. What about the reconciliation job that has no user?"

It gets a workload identity instead of a user identity, and the authorisation rule distinguishes the two.

The job runs under its own service account with a client-credentials token from the identity provider — a token with a subject of reconciliation-job and a scope of refunds:system — and the refund endpoint accepts either a user token with refunds:issue and a support role, or a system token with refunds:system from a listed workload.

The audit log records the workload as the actor. What I would not do is create a fake user account for the job, which is how "internal only" endpoints tend to acquire a shared password nobody rotates.

The policy is expressed in Spring Security as two authorisation rules on the endpoint, and the mesh policy from stage two additionally restricts which workloads can even reach it, so a system token stolen from the job cannot be used from a different pod.

"How would you verify, six months later, that the endpoint is still protected?"

With a test that tries to break it, run automatically.

A scheduled job in the security namespace starts a pod with no mesh identity and a pod with a generic identity and attempts POST /refunds on the payment service; both must fail, one at the network layer and one at the mesh layer, and a success pages the security channel.

A second check calls the endpoint with a valid mTLS identity but no token and expects a 401. These are the same tests as the chaos programme's regression suite, applied to security controls, and they catch the day someone deletes the NetworkPolicy to debug something.

I would also keep the audit-mode logging on for denied calls, because a rise in denials is an early sign of either a new legitimate caller that needs adding or something probing.

A policy that nobody tests decays the same way a fallback that nobody exercises does.

Q113 · Design. "Design inter-service authentication and authorisation for the order platform: user requests from the gateway, service-to-service calls, asynchronous consumers, and background jobs."

Reveal answer

Strong answer Requirements:

  • every call carries a verifiable workload identity and, where a user is involved, a verifiable user identity;
  • tokens are short-lived;
  • no service holds long-lived credentials;
  • async work keeps the user context.

Design, one layer at a time:

  1. Workload identity: the mesh issues SPIFFE-style certificates to every pod and enforces mTLS. Authorisation policies at the mesh layer state which service identities may call which paths (only order may call payment's charge; only support may call refund).
  2. User identity: the gateway validates the user's OIDC access token from the identity provider and forwards it. Each service validates the signature against the provider's published keys (cached JWKS) and checks audience and scope with Spring Security's JWT resource-server support.
  3. Calls on behalf of a user: the caller performs an OAuth token exchange to get a token scoped to the target service with the user's identity preserved, so a token stolen from one service cannot be replayed against another.
  4. Asynchronous consumers: the producing service puts the acting user's id and a signed, minimal claims set into the message headers. Consumers verify the signature and apply authorisation to the user, not to the producer.
  5. Background jobs: they run under their own workload identity with a client-credentials token whose scope is limited to what the job does.
  6. Audit: every authorised action logs workload identity, user id, and trace id.

Trade-offs: a mesh, an identity provider that supports token exchange, and key rotation to operate. What I would not do is a shared static API key between services; it is the first thing an attacker finds and the last thing anyone rotates.

Picture it One order placement and one refund event travelling through the platform, with the identity each hop proves, and what a stolen token or an identity-provider outage does.

The setup: A customer places an order: browser, gateway, order service, payment service, and an OrderPlaced event consumed later.

Make the invisible visible: The credential each hop carries and what it proves.

identity at each hopruns offline
# illustrative output
Browser --JWT(sub=u42, aud=gateway, 10 min)--> Gateway     validates signature, exp, aud       ✓
Gateway --same JWT------------------------> Order          cached JWKS, aud=order              ✓
Order   --exchanged JWT(sub=u42, aud=payment, 5 min)--> Payment
          mTLS: caller id spiffe://cluster.local/ns/orders/sa/order-service   ✓ may call /charges
Order   --OrderPlaced hdr{user=u42, svc=order, ts, sig}--> Broker --> Notification
          Notification verifies sig with order's key, authorises u42             ✓

The trace: A token stolen from the order service and replayed against inventory, then against payment from a pod without the order identity.

replay attemptsruns offline
# illustrative output
replay JWT(aud=payment) at inventory   -> 401  audience mismatch      ✓ blocked
replay JWT(aud=payment) at payment
   from a pod with identity image-resizer -> 403  mesh policy: caller not allowed   ✓ blocked
replay the same token 6 min later         -> 401  expired            ✓ blocked

What you see: The identity provider goes down with 15-minute access tokens: tokens issued before the outage keep working until they expire, so the failure arrives as a cliff.

outage timelineruns offline
# illustrative output
t=0 min    IdP down        users with valid token: 100%   token exchanges: failing   logins: failing
t=7.5 min  IdP down        users with valid token: ~50%   (tokens issued uniformly over the last 15 min)
t=15 min   IdP down        users with valid token:  0%    cliff: everyone is logged out

Why: Validation uses cached keys and needs no call, but issuing, refreshing and exchanging all need the provider.

The fix: Cache exchanged tokens for their lifetime, let jobs renew client-credentials tokens early, alert on the provider well before the cliff, and run the provider redundantly across zones. Do not accept expired tokens.

Symptom, root cause, action
SymptomRoot causeAction
A token stolen from one service works on anotherBroad audience, no exchangeToken exchange per hop with a narrow aud
Consumer cannot validate a forwarded JWT an hour laterJWT lifetime is minutesSigned minimal claims in message headers
Users logged out at the same minuteIdentity provider outage past token lifetimeRedundant provider, cached exchanged tokens, early alert
Services share one static API keyNo workload identityMesh certificates and client-credentials tokens

Land it Workload identity from the mesh, user identity from short-lived tokens exchanged per hop, and signed claims on messages — so every action in the platform can answer "which service, for which user".

Likely follow-ups
"How does a service validate a JWT without calling the identity provider on every request?"

The token is signed with the provider's private key, and the provider publishes the matching public keys at a JWKS endpoint — a JSON document of keys, each with a key id.

JwtDecoderConfig.javaruns offline
// ✅ FIX: validate locally against the cached JWKS, no call to the provider per request
@Bean
JwtDecoder jwtDecoder(@Value("${jwks-uri}") String jwksUri) {
    return NimbusJwtDecoder.withJwkSetUri(jwksUri).build();
}
// Result: signature, exp and nbf are checked in microseconds; a token with an unknown kid triggers a key refresh

The service fetches that document once, caches it, and validates every token's signature locally against the key whose id matches the token's kid header, which is a few microseconds of cryptography with no network call.

Spring Security's NimbusJwtDecoder does this with spring.security.oauth2.resourceserver.jwt.jwk-set-uri or the issuer URI, and it refreshes the cache when it sees an unknown key id, which is how key rotation works without downtime: the provider adds a new key, signs with it, and services fetch the new set on the first unfamiliar token.

The trade-off is revocation: a token is valid until it expires whether or not the user has been logged out, so access tokens are short-lived — five to fifteen minutes — and anything longer uses a refresh token that the provider can revoke.

"What goes in the signed claims on a Kafka message, and why not just forward the user's JWT?"

The user's JWT expires in minutes, and the consumer may run an hour later, so a forwarded token would be invalid by the time it is checked.

Instead the producer writes a small set of headers: the user id, the acting service's identity, a timestamp, and a signature over those and the message key made with the producing service's key — either the same private key the mesh issued it, or a dedicated signing key from the secrets manager.

Kafka record headersruns offline
# illustrative output
OrderPlaced  key=o-1001
  x-user-id=u42   x-acting-service=order   x-ts=1731700000   x-sig=MEUCIQD...
# consumer: verify x-sig over (key, user, service, ts) with order's public key, then authorise u42

The consumer verifies the signature against the producing service's public key, obtained from the same JWKS-style endpoint the platform runs for service keys, and then applies its authorisation to the user id: may this user have triggered a refund.

The claims are deliberately minimal — no roles, because roles change and the consumer should look them up if it needs them. This gives the consumer non-repudiation about who caused the message without depending on a token's lifetime.

"The identity provider is down. What still works?"

Everything that has a valid token already, for as long as those tokens last. Services validate tokens with cached keys, so existing sessions keep working.

What stops is issuing: new logins, token refreshes when access tokens expire, token exchanges between services, and client-credentials tokens for jobs starting fresh.

The practical consequence is a cliff after the access-token lifetime — at fifteen minutes, users start being logged out and services start failing exchanges.

To soften the cliff:

  • exchanged tokens are cached for their lifetime, so a brief outage does not hit every hop;
  • jobs cache their client-credentials token and renew early;
  • the platform's alert on the identity provider fires well before the cliff.

What I would not do is fall back to accepting expired tokens, because that turns an outage into a security hole. The identity provider is a tier-one dependency, and it gets tier-one redundancy — multiple instances across zones — for that reason.

"What would you cut under time pressure?"

The token exchange per hop and the signed claims on messages, in that order, but not mTLS or the JWT validation at every service.

A first version has mesh mTLS with authorisation policies naming allowed callers, gateway validation of the user's token, and each service validating the forwarded user token with audience checks — the forwarded token has a broad audience, and I accept that for a month.

Messages carry the user id as a plain header and the consumer trusts it because the producer's identity is already established by mTLS on the produce path and by the topic's ACL, which is weaker than a signature but bounded.

Background jobs get client-credentials tokens from day one because it is a configuration, not a build.

Token exchange comes when the platform has a service handling money or personal data whose compromise must not yield tokens for anything else, which is the payment service, so it comes soon.

Q114 · Scenario. "The end-to-end suite spins up 22 services with Testcontainers, takes 45 minutes, and fails about one run in four for reasons nobody can reproduce. Developers have started ignoring it. What do you do?"

Reveal answer

Strong answer A test suite that is slow and flaky is worse than no suite, because it trains people to ignore red.

Evidence: the failure history by test and by cause (timeouts waiting for containers, port collisions, ordering assumptions, real bugs), and how much of the suite's coverage is duplicated by lower-level tests.

Causes ranked:

  1. Redundant scope: the suite tests service interactions that contract tests would cover in seconds, so it is both slow and redundant.
  2. Sleeps instead of waits: startup ordering and readiness are handled by sleeps rather than health waits, producing timing failures.
  3. Shared state: tests share the same database and the same topic, so they interfere when run in parallel.
  4. Starved runners: the suite runs on shared CI runners that are starved.

The plan, in four steps:

  1. Quarantine: move the suite off the merge gate to a nightly run with a named owner, so red means something again.
  2. Replace: for each pair of services the suite exercises, write a consumer-driven contract test and delete the corresponding end-to-end case. That usually removes most of the suite.
  3. Keep a thin set: five to ten business journeys run against a deployed staging environment on every deploy, and continuously in production as synthetic checks, with proper readiness waits and isolated data per run.
  4. Make flakiness visible: a test that fails without a code change is a bug in the test, ticketed like any other.

The trade-off is a few weeks of contract-writing; the return is a merge gate that runs in minutes and is believed.

Picture it The suite's numbers at three moments, the flake arithmetic that explains one red run in four, and a contract test replacing one end-to-end case (see consumer-driven contracts).

The setup: Today every merge starts 22 services with Testcontainers and runs the end-to-end suite, including the order to payment to inventory journey.

Make the invisible visible: How the gate changes over the plan.

suite numbers at three momentsruns offline
# illustrative output
                        today          week 2 (quarantine)      week 6 (contracts + thin set)
merge gate duration     45 min         6 min (unit + slice)     9 min (+ contract tests)
end-to-end containers   22 per run    22, nightly only         0 on the gate; 8 journeys on staging
red runs with no bug    ~25 %          <5 % on the gate         <5 %
quarantined tests       0              all e2e (nightly)        flaky ones only, each ticketed

The trace: Why a suite of mostly good tests still fails one run in four: small per-test flake rates multiply.

flake arithmeticruns offline
P(run is green) = (1 - p) ^ tests
200 tests, p = 0.5 %   ->  0.995^200 = 0.37   ->  63 % of runs red   (the text's example)
200 tests, p = 0.14 %  ->  0.9986^200 = 0.75  ->  25 % of runs red   (this team's one-in-four)
sleeps: 40 containers x 10 s = 400 s of waiting, about 7 minutes, and still too short on a loaded runner

What you see: A boundary check as a contract test: the order service's expectation of payment is checked against the real payment build, in seconds, with no containers.

contract test flowruns offline
order build:   OrderClientContractTest writes order-payment contract
               POST /charges {orderId, amount} -> 201 {id, status}              ✓  3 s
payment build: verifies the contract against the real controller, stubbed DB    ✓  5 s
payment dev renames "status" to "state"   -> provider verification              ✗  fails before merge

Why: End-to-end suites test every boundary through everything else; a contract tests one boundary alone, so a failure names the boundary.

The fix: Contracts for the pairs, a thin set of journeys with proper waits and unique data, and flake tracking.

Symptom, root cause, action
SymptomRoot causeAction
Connection refused in the first secondsSleep too short on a loaded runnerUse a wait strategy such as Wait.forHttp on the readiness endpoint
Passes alone, fails in parallelShared database or topicUnique ids per test, unique consumer group and topic suffix
Timeouts that pass on retryStarved CI runnerDedicated larger nodes for the job
Fails when another team deploysShared staging environmentEphemeral environment per pipeline run

Land it Shrink the end-to-end suite to the journeys that need it, push the boundary checks into contracts, and treat every flaky failure as a bug — a gate is only useful if people trust it.

Likely follow-ups
"What does a proper readiness wait look like in Testcontainers, versus a sleep?"

A sleep guesses; a wait strategy checks. Testcontainers' GenericContainer.waitingFor(...) takes a strategy that blocks until a condition is true: Wait.forHttp("/actuator/health/readiness").forStatusCode(200) for a service, Wait.forListeningPort() for a broker, or Wait.forLogMessage(".*started.*", 1) for something with no health endpoint.

PaymentContainer.javaruns offline
GenericContainer<?> payment = new GenericContainer<>("shop/payment:1.4")
    .withExposedPorts(8080)
    // ❌ TRAP: Thread.sleep(10_000) after start() guesses, and is wrong twice
    // ✅ FIX: block until the readiness endpoint answers 200
    .waitingFor(Wait.forHttp("/actuator/health/readiness").forStatusCode(200));
// Result: starts exactly as fast as it can; a container that never becomes ready fails with a clear message

The modules — PostgreSQLContainer, KafkaContainer — ship with the right strategy built in. For dependencies between containers, dependsOn(other) starts them in order and waits for each.

A sleep of ten seconds is wrong twice: too short on a loaded CI runner and the container is not ready, too long on a fast one and forty containers waste seven minutes.

With wait strategies the startup takes exactly as long as it needs and fails with a clear message when a container never becomes ready, which is a real bug rather than a timing one. That change alone usually removes a third of the flakiness.

"How do you isolate data per test so tests can run in parallel?"

Every test creates what it needs with unique identifiers and never assumes the world is empty.

An order test creates its own customer with a random id rather than using "customer 1", and asserts on its own ids, so two tests running at once do not see each other.

For the database, each test class gets its own schema or the suite truncates between tests only when running serially; in parallel, unique data is the only approach that scales.

For Kafka, each test uses a unique consumer group id and, where possible, a topic with a unique suffix created at test start, so a message from another test is never consumed by mistake. Time-based assertions use the test's own timestamps.

Testcontainers reuse across test classes keeps the container start cost down, and the data isolation is what makes reuse safe. The check that it worked is running the suite with -Djunit.jupiter.execution.parallel.enabled=true ten times; a test that fails only in parallel has a shared-state bug.

"How do you quantify flakiness, and what threshold triggers action?"

The pipeline records every test's result with a hash of the commit, and a nightly job computes, per test, the rate at which it failed on a commit where it also passed on retry or on the same code — that is the flake rate, distinct from the failure rate.

A dashboard lists tests by flake rate, and any test above 1% over the last hundred runs is automatically quarantined: moved to a separate job that does not block merges, with a ticket opened against the owning team.

Below 1% the cost of chasing is higher than the cost of a rerun.

The suite-level number I watch is the probability that a green commit shows red — with 200 tests each flaking at 0.5%, that is a 63% chance per run, which is roughly where this team was.

The target is a suite whose false-red rate is under 5%, because above that people stop reading failures.

"The fix didn't work — you moved to contracts and a thin suite, and the thin suite still fails one run in four. What is left?"

Then the flakiness is in the environment, not the tests.

Ten tests failing at that rate means either the staging environment they run against is unstable — someone else's deploy, a database shared with manual testing, a third-party sandbox that rate-limits — or the CI runners are starved and timeouts fire.

I would look at the failure reasons: timeouts point at the runner or the environment, assertion failures point at the tests.

For a shared staging environment the fix is an ephemeral environment per pipeline run — a namespace with the services under test deployed from the branch and everything else pointing at stable versions — which costs cluster capacity but removes interference.

For third-party sandboxes, a stub in the ephemeral environment. For runners, dedicated larger nodes for this job. And I would check whether the ten journeys are still too coupled: a journey that touches every service is as fragile as the old suite, only shorter.

Q115. "When would you NOT canary a change?"

Reveal answer

Strong answer A canary needs three things: enough traffic to judge, metrics that reflect the change, and the ability to run both versions side by side. When any is missing, the canary gives false confidence.

When a canary is the wrong tool:

  1. Low-traffic services: at a hundred requests an hour, a 5% canary sees five requests, and no analysis is meaningful. Use blue/green with a manual smoke test instead.
  2. Changes not observable in request metrics: a change to a nightly batch, a logging format, or a library upgrade with no behavioural change. Canary metrics will say nothing, so test them differently.
  3. Changes where two versions cannot coexist: a Kafka consumer whose new version uses a different partition-assignment logic or message format, a stateful service with an incompatible on-disk format, a database migration that the old code cannot read. Split the change into compatible steps and canary each step, or deploy blue/green as an atomic switch.
  4. Emergency fixes during an incident: a thirty-minute rollout schedule extends the outage. A shortened schedule or a direct rollout with a human watching is the right trade, done rarely and recorded.
  5. Changes gated by a feature flag: the flag is the canary, at the feature level, and running both is double work.

What I would not do is skip the canary because the change is "small"; small changes cause a healthy share of outages precisely because nobody watched them.

Picture it Three candidate changes on the order platform: how many requests a canary actually judges, and why a producer canary can look green while every consumer breaks (see the canary block and the blue/green block).

The setup: A 5% canary for the inventory reconcile job, a 10% canary for payment, and a canary of an order producer that changes the OrderPlaced message format.

Make the invisible visible: Count what the canary judges. At 1% error rate the expected errors in the canary slice must clearly beat the noise.

canary sample at three traffic levelsruns offline
# illustrative output
service             overall traffic   canary share   window   requests judged   errors if rate is 1 %
inventory-reconcile 100 / hour        5 %            1 hour   5                 0.05      -> theatre
order-lite          1 / s             10 %           10 min   60                0.6       -> one unlucky request
payment             33 / s            10 %           10 min   ~1,980            ~20 vs ~2 at 0.1 %   -> unmistakable

The trace: A canary of the producer with a format change: the producer's own metrics stay clean, and every old consumer reads the new event.

Kafka topic orders.eventsruns offline
offset 100  OrderPlaced v1 {"total": 49.0}                                     v1 consumers ✓  v2 consumers ✓
offset 101  OrderPlaced v2 {"total": {"amount": 49.0, "currency": "EUR"}}     v1 consumers ✗ cannot parse "total"
            written by the canary pod (5% of producers)                       v2 consumers ✓
producer canary error rate: 0.0 %  (green)     inventory v1 parse errors: ~5 % of events (red, but not judged)

What you see: The signal lives in the consumers, not in the metric the canary judges.

Why: Two versions of the producer put two formats on the same topic at the same time, and the canary assumes both can coexist.

The fix: Split into compatible steps: first deploy readers for both formats everywhere, then switch the producer. Each step is safe with both versions running.

compatible stepsruns offline
step 1  deploy consumers that read v1 and v2        canary ✓  (behaviour unchanged for v1 events)
step 2  switch producer to write v2                  canary ✓  (every consumer already reads v2)
step 3  later: remove the v1 reader                  canary ✓
Situation, why a canary fails, what to use
SituationWhy a canary gives false confidenceUse instead
100 requests an hour5 judged requestsBlue/green and a manual smoke test
Nightly batch or logging changeRequest metrics do not moveTest the job itself, diff the output
Format or on-disk changeTwo versions cannot coexistCompatible steps, or an atomic blue/green switch
Change behind a feature flagThe flag already ramps the featureRamp the flag, watch the feature's metric
Fix during an incidentThirty minutes extends the outageHotfix path: 25% for three minutes, human watching

Land it Canary when traffic, metrics, and coexistence allow a real judgement, and choose a different safety net — a flag, a blue/green switch, a compatible split — when they do not.

Likely follow-ups
"What is the minimum traffic for a canary to be meaningful? Give me the arithmetic."

It depends on the failure rate you want to detect.

To notice an error rate rising from 0.1% to 1% with reasonable confidence, the canary needs enough requests that one percent of them is well above the noise — roughly a few thousand requests in the judged window, because at 2,000 requests a 1% rate is 20 errors versus an expected 2, which is unmistakable, while at 200 requests it is 2 versus 0.2, which is one unlucky request.

So a 10% canary for ten minutes needs about 20,000 total requests in ten minutes, or 33 requests a second overall.

Below that, extend the duration or the percentage until the count is reached, and below about one request a second overall, no reasonable duration gets there and the canary is theatre.

For latency the numbers are gentler, because every request contributes a sample; a few hundred is enough for a p95 comparison. I encode the floor in the analysis as a minimum sample count, which fails the analysis as inconclusive rather than passing it.

"The library upgrade with no behavioural change — why not canary it anyway? It is cheap."

You should deploy it through the same pipeline, and the canary will run; the point is that its result means little, so it should not be the thing you rely on.

A library upgrade's risks are things a short canary cannot see:

  • memory behaviour, which shows up as a slow leak over hours;
  • startup time;
  • a changed default in a connection pool;
  • a serialisation difference in a rare type, which fails on an unusual input or on nothing at all until a dependency hiccups.

A thirty-minute canary on error rate and p99 sees none of those. What catches them is the integration suite for serialisation, a soak test in staging for memory, and a diff of effective configuration before and after for defaults.

So the honest answer is: yes, let the canary run, because it costs nothing and might catch a surprise, but do the other checks because the canary is not designed for this risk.

The mistake is the reverse — skipping the soak test because "the canary passed".

"How do you canary a Kafka consumer whose new version changes the message handling?"

By partition share rather than by traffic percentage, and only if both versions can process the same messages.

A consumer canary is one pod of the new version joining the group, which takes its share of partitions — with 24 partitions and 24 pods, one pod is 4% of the messages.

The analysis watches error rate, processing latency, and lag on the canary's partitions versus the rest, using the version tag. Rollback is stopping the pod, which rebalances its partitions back.

consumer canary evidenceruns offline
# illustrative output
group inventory: 24 partitions, 24 pods, 1 canary pod
pod inventory-v2-x   partitions: 1 (4 %)   lag 12   errors 0/min   version=v2
23 other pods        partitions: 23        lag ~10  errors 0/min   version=v1

The precondition is that the new handler is idempotent and produces the same outputs for the same inputs, because a rollback redelivers from the last commit; and that the message format has not changed in a way the old version cannot read, which is the coexistence rule.

If the change is the format itself, it is split: first deploy readers for both formats everywhere, then switch the producer, and neither step needs the two versions to disagree about a message.

"An incident is in progress and the fix is ready. Do you skip the canary or not?"

I run a shortened one, and the decision is explicit.

During an incident the cost of the rollout schedule is measured in minutes of continued outage, so a thirty-minute canary is wrong; but a fix deployed straight to 100% that makes things worse is the story of many second outages.

The compromise is the hotfix path: 25% for three minutes judged on error rate only, then 100%, with a human watching the dashboard instead of the full analysis. That takes five minutes and catches the fix that crashes on startup or doubles the error rate.

The incident commander makes the call, it is logged in the incident channel, and the post-mortem reviews whether it was right.

What I would not do is make skipping the canary a normal option available to anyone under pressure, because "it was urgent" becomes the reason every deploy skips it within a quarter. The hotfix path exists so that the fast option is still a safe one.

10 · DrillProduction Scenarios & System Design — Q116–Q150

The last thirty-five questions are the senior round proper: incidents described the way an on-call engineer meets them, and design prompts that ask for a whole system with its trade-offs. Answer the scenarios in diagnosis order — symptom, evidence, ranked causes, fix, prevention — and the designs with requirements first, then the design, then what you would not do and why. Several reach back to the Distributed Systems primer, Chapter E3, and Chapter E8.

Drill · Production incidents

These scenarios test whether you can find the one component whose failure explains everything, and whether your fix removes the class of failure rather than the instance.

Q116 · Scenario. "The config server was unreachable for eight minutes during a network change. Every service that restarted or scaled during that window failed to start, and two services that did not restart began returning errors anyway. Explain both."

Reveal answer

Strong answer Two different couplings to one dependency.

The services that failed to start fetched configuration at startup from the config server with no fallback. They had:

  • no cached copy on disk;
  • no bundled defaults;
  • a startup that treats "cannot fetch config" as fatal.

So an eight-minute config outage became an eight-minute inability to scale or recover, which is the worst moment to lose that ability.

Evidence: the startup logs showing the fetch failure and the config client's settings (fail-fast, retry, and whether a local cache is configured).

The two services that degraded without restarting had a runtime dependency: a periodic refresh of configuration that, on failure, either reset values to defaults (a known trap with some refresh implementations) or blocked a thread that held a lock.

Evidence: their refresh logs at the outage's start.

Causes ranked:

  • config treated as a runtime dependency rather than an artefact;
  • no local fallback;
  • fail-fast startup with no retry.

Fix:

  1. services keep the last good configuration on disk and start from it when the server is unreachable;
  2. startup retries with backoff rather than failing;
  3. runtime refresh keeps current values on failure and alerts.

Better still, move static configuration into the deployment (ConfigMaps rendered by the pipeline) so startup needs nothing over the network, and reserve the config service for values that must change at runtime.

Prevention: a game day where the config server is stopped and services are expected to scale and restart anyway.

Picture it An eight-minute config-server outage on the order platform: pods that cannot start, a refresh that resets a timeout, and the capacity arithmetic that turns both into errors (see externalised config).

The setup: The order service runs 6 pods at 100 requests per second each. At 10:00 the config server becomes unreachable, a campaign pushes load to 800 requests per second, and the autoscaler asks for 10 pods.

Make the invisible visible: Who depends on the config server, and when.

topology and blast radiusruns offline
# illustrative output
                     config-server   X unreachable 10:00 - 10:08
                      /     |     \
   order (restart)  order (scale-out)  inventory, payment (running, periodic refresh)
   fetch at startup: ✗ fatal          refresh fails: ✗ resets to defaults / blocks a thread
blast radius: every pod that starts, plus every service that refreshes

The trace: Capacity at four moments.

Order service at four moments (illustrative)
TimeDemand rpsPods ready / desiredCapacity rpsShortfall
10:004506 / 6600none
10:038005 / 10 (1 pod restarted, 4 new pods crash-loop)500300 rps (37%)
10:088005 / 10500300 rps (37%)
10:09 (server back)80010 / 101000none

What you see: The startup log of a new pod, and the refresh that reset a value.

pod log and refreshruns offline
# illustrative output
ConfigServicePropertySourceLocator: Could not locate PropertySource and the fail fast property is set, failing
inventory.client.timeout   before refresh: 800 ms (from config server)
                           after failed refresh: 30000 ms (bundled default)
Little's law: 100 rps x 0.8 s = 80 busy threads;  100 rps x 30 s = 3,000 busy threads on a pool of 200

Why: Configuration was fetched over the network on the startup path and again on the refresh path, with no last-good copy on either.

The fix: Last-good copy on disk, retry with backoff, refresh that keeps current values on failure and alerts, and static configuration rendered into ConfigMaps.

What you see now: The same outage after the fix.

pod log and refreshruns offline
# illustrative output
config client: server unreachable after retries, starting from /var/cache/config/last-good.yaml (age 3 h)  metric config_fallback=1
order pods ready 10 / 10 at 10:04; inventory.client.timeout stays 800 ms; alert: config-server down
Symptom, root cause, action
SymptomRoot causeAction
New pods crash-loop during an outagefail-fast startup, no fallbackLast-good file, retry with backoff, ConfigMaps for static config
Running service degrades at refreshFailed refresh resets to defaultsKeep current values on failure and alert
Fallback used, wrong valuesCache or baked defaults older than a changeRefresh the cache every interval, alert on config age

Land it Anything a service needs to start is an availability dependency, and configuration should be a file the pod already has, not a call it hopes will succeed.

Likely follow-ups
"Name the Spring Cloud Config settings involved and what each one does in this incident."

spring.cloud.config.fail-fast=true is the one that made startup fatal: it tells the client to abort the application if it cannot reach the config server, and it is often set on purpose so that a misconfigured service does not start with defaults.

application.ymlruns offline
spring:
  cloud:
    config:
      fail-fast: true            # ❌ TRAP: abort startup if the server is unreachable
      retry:
        max-attempts: 6          # default: six attempts over a few seconds, far short of 8 minutes
        initial-interval: 1000
# ✅ FIX: do not rely on this alone: start from the last-good file or from ConfigMaps

spring.cloud.config.retry.max-attempts and spring.cloud.config.retry.initial-interval control the retry before that abort; the default is six attempts over a few seconds, which does not cover an eight-minute outage.

For the runtime side, spring.cloud.config.refresh or the Spring Cloud Bus refresh trigger causes beans annotated @RefreshScope to be rebuilt on the next access after a refresh event; if the refresh fetched an empty or failed result and the implementation replaced the environment rather than keeping it, values reverted.

As of Aug 2026, Spring Cloud Config's client keeps the last values on a failed fetch, but a custom refresh listener or an older version may not, which is what I would check in those two services' logs.

"How do you keep a last-good copy on disk, and how stale is too stale?"

The config client writes every successfully fetched configuration to a local file — /var/cache/config/last-good.yaml with the fetch timestamp — and at startup, if the server is unreachable after the retry window, it loads from that file and logs a loud warning and increments a metric.

On Kubernetes that file lives on the pod's ephemeral disk, so a brand-new pod on a fresh node has no cached copy; for that case the container image bundles the defaults for the environment at build time, and the pipeline refreshes them on every build, which makes the image itself the last resort.

"Too stale" is a policy: I set a maximum age of 24 hours on the cached copy, after which the service starts but marks itself degraded in its health detail, so an operator sees it.

Configuration that is safety-critical — a kill switch — is not in this system at all; it is a flag with its own fallback. The test is the game day: stop the config server and scale a service up.

"Why not put everything in ConfigMaps and delete the config server?"

For most configuration I would, and that is the recommendation.

The config server earns its place only for values that must change at runtime across many services without a redeploy — and those are better served by a flag service with a local cache, which has the fallback behaviour built in.

What ConfigMaps cannot do easily is a change that takes effect without a pod restart; a mounted ConfigMap file does update in place, and Spring Cloud Kubernetes can watch it, but the default is that a ConfigMap change does nothing until the pods roll.

For a platform where "change a timeout at 2 a.m. without deploying" is a real need, the flag service covers it.

So the end state is ConfigMaps rendered from git by the pipeline for static configuration, a flag service for runtime switches, the secrets manager for secrets, and no config server.

The migration is one service at a time, with the config server left running until the last consumer is gone.

"The fix didn't work — services now start from cache, but during the next outage they started with the wrong values. Why?"

Because the cache was stale in a way that mattered: the last-good copy on that pod's disk was from before a configuration change, so the pod came up with an old timeout or an old endpoint.

Two causes to check.

First, the cache is per pod, and pods that had not fetched since the change had an old copy — the fix is that a successful fetch happens on every refresh interval, not just at startup, so the cache is never older than the refresh period.

Second, the bundled image defaults were used instead of the disk cache because the pod was new, and the image was built before the change — the fix is that a configuration change triggers a rebuild of the defaults, or that the defaults are rendered into the ConfigMap by the pipeline rather than baked into the image.

Either way the real lesson is that the fallback's freshness has to be monitored: a metric of the cached config's age, per pod, with an alert when it exceeds the refresh interval.

Q117 · Scenario. "Since tracing was enabled last week, the order service's memory climbs steadily and it is restarted by the out-of-memory killer every nine hours. Nothing else changed. Where is the memory going?"

Reveal answer

Strong answer A steady climb that started with tracing points at spans that are created faster than they are exported or that are never ended.

Evidence: a heap dump shows the retained objects — span data, an exporter's queue; the exporter's metrics (queue size, dropped spans, export failures); and the collector's reachability from the pod.

Causes ranked:

  1. Exporter cannot deliver: the OTLP exporter cannot reach the collector (wrong endpoint, network policy, TLS), so its batch queue fills. The OpenTelemetry batch processor drops beyond a bound, but a misconfigured or unbounded queue, or a very large bound with large spans, retains gigabytes.
  2. Spans never ended: a custom span around an asynchronous operation whose completion callback does not close it, so every request leaks a span.
  3. Sampling and size: sampling at 100% on a high-volume path with spans carrying large attributes (full request bodies as attributes is a common mistake).
  4. Per-record spans: the Kafka listener observation creating a span per record with no batch end.

Fix:

  1. correct the exporter endpoint and confirm exports succeed;
  2. bound the batch processor's queue explicitly and alert on dropped spans;
  3. find the unended span with a span-count metric per name;
  4. strip large attributes;
  5. sample.

Prevention: enabling tracing is a change to a service's memory profile, and the rollout should have been canaried with memory as a judged metric.

Picture it The order service's memory at three moments, the arithmetic that turns nine hours to OOM into a leak per request, and which hypothesis each number points to (see distributed tracing).

The setup: Tracing was enabled last week. The order service has a 2 GB container limit, a 600 MB baseline and 200 requests per second.

Make the invisible visible: Memory and the exporter queue over the nine hours.

memory at three momentsruns offline
# illustrative output
hour 0     heap 600 MB    container RSS 0.9 GB    exporter queue 0 / 2048
hour 4.5   heap 1.3 GB    container RSS 1.6 GB    exporter queue 2048 / 2048 (bounded, dropped=1.2M)
hour 9     heap 2.0 GB    container RSS 2.1 GB    OOM kill

The trace: The numbers narrow the cause.

leak arithmeticruns offline
leak = 2.0 GB - 0.6 GB = 1.4 GB over 9 h = 32,400 s  ->  ~43 KB/s
43 KB/s / 200 rps  = ~215 bytes per request     (a whole span is ~1 KB or more)
queue bound: 2048 spans x ~2 KB = ~4 MB  ->  a bounded queue cannot hold 1.4 GB
~215 B per request  => a small object per request (an MDC entry, a leaked scope, an attribute on a long-lived parent span)
~1 KB per request   => whole spans are being retained: unended spans move to the top

What you see: A heap histogram that names the retained class, and the metric that names the span.

class histogram and span gaugeruns offline
# illustrative output
 num   #instances    #bytes  class name
   1:   1,240,000  ~1.2 GB   io.opentelemetry.sdk.trace.SdkSpan
started-minus-ended by span name:  inventory.reserve  +1,240,000  (climbing)   others ~0

Why: A span that is started and never ended is never exported, and whatever holds it keeps it alive.

The fix: End the span on every path.

InventoryClient.javaruns offline
Span span = tracer.spanBuilder("inventory.reserve").startSpan();
CompletableFuture<Void> f = inventory.reserveAsync(order);
// ❌ TRAP: thenRun does not run when the future fails, so the span is never ended
f.thenRun(span::end);
// ✅ FIX: end on success and failure
f.whenComplete((r, ex) -> { if (ex != null) span.recordException(ex); span.end(); });

What you see now: The gauge is flat and the heap sawtooths.

class histogram and span gaugeruns offline
# illustrative output
started-minus-ended by span name:  inventory.reserve  ~0 (steady)
hour 9   heap 0.7 GB, sawtooth   no OOM kill
Symptom, root cause, action
SymptomRoot causeAction
Queue full, dropped counter risingCollector unreachableFix endpoint, TLS or policy; alert on drops
Gauge for one span name climbsSpan never endedend() in whenComplete or finally; close scopes
Heap flat, RSS climbsNative memory (direct buffers, threads, metaspace)NativeMemoryTracking and jcmd VM.native_memory
Retained spans are hugeRequest bodies as attributesStrip attributes, sample

Land it Telemetry is a producer with a queue like any other, and an exporter that cannot deliver will either drop or grow — I want it configured to drop and to tell me.

Likely follow-ups
"Which exporter settings bound the queue, and what do the defaults look like?"

The OpenTelemetry SDK's BatchSpanProcessor has four settings: otel.bsp.max.queue.size, the maximum number of spans buffered before export, default 2048; otel.bsp.max.export.batch.size, default 512; otel.bsp.schedule.delay, default 5 seconds; and otel.bsp.export.timeout, default 30 seconds.

effective exporter settingsruns offline
# illustrative output
OTEL_BSP_MAX_QUEUE_SIZE=2048        # default
OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512  # default
OTEL_BSP_SCHEDULE_DELAY=5000        # ms, default
OTEL_BSP_EXPORT_TIMEOUT=30000       # ms, default
# a queue size someone raised to 1000000 would explain gigabytes

When the queue is full, new spans are dropped and a counter — otel.sdk.processor.span.queue.size and the dropped count — increments. With those defaults the queue holds 2048 spans, a few megabytes at most, so a plain OpenTelemetry setup cannot leak gigabytes through the queue.

That tells me to look elsewhere: a Micrometer Tracing bridge with a different exporter configuration, an exporter that retries with an unbounded retry queue, or a queue size someone raised to a million to "avoid dropping spans".

The first thing I would check is the effective value of that queue-size property in the running pod, via the actuator's environment endpoint.

"How do you find an unended span without reading every instrumentation?"

With the heap dump and one metric.

In the heap dump, unended spans are SdkSpan objects that are still referenced from somewhere other than the exporter queue — usually from a Scope that was never closed, held in a thread-local of a pooled thread, or from a CompletableFuture callback that never ran.

A histogram of retained objects by class shows tens of thousands of span objects with their names, and the name is the culprit. The metric is simpler: a gauge of started-minus-ended spans per span name, which the platform's tracing library can expose by wrapping the tracer.

A name whose gauge climbs steadily is the unended one. The common code pattern is a manual tracer.spanBuilder(...).startSpan() around an asynchronous call with span.end() in a callback that is skipped on the exception path.

The fix is try-with-resources on the scope and end() in a finally or a whenComplete.

"Nine hours to OOM — what does that number tell you about the rate?"

It gives me the leak rate and therefore a hypothesis about what leaks. If the container limit is 2 gigabytes and the baseline is 600 megabytes, the leak is about 1.4 gigabytes in nine hours, or roughly 43 kilobytes a second.

At 200 requests a second that is about 200 bytes per request, which is too small for a whole span per request — a span with attributes is a kilobyte or more — and too regular for a queue that only fills when the collector is down.

Two hundred bytes per request looks like a small object per request: an MDC entry not cleared, a scope not closed leaving a context object, or an attribute added to a long-lived parent span.

If instead the rate matches a kilobyte per request, it is whole spans, and the unended-span hypothesis moves to the top.

I would confirm by comparing the leak rate with the request rate over the day: a leak that follows traffic is per-request; one that is flat regardless of traffic is a timer or a batch job.

"The fix didn't work — you bounded the queue and stripped attributes, and memory still climbs. Where next?"

Then the memory may not be on the heap at all.

The out-of-memory killer acts on the container's total memory, and a JVM whose heap is fixed at 1 gigabyte can still be killed if native memory grows. Candidates:

  • Netty direct buffers used by the gRPC exporter;
  • thread stacks from an exporter creating threads;
  • metaspace from a classloader leak.

I would compare the JVM's reported heap use with the container's RSS over the nine hours; if the heap is flat and RSS climbs, it is native. Native memory tracking — -XX:NativeMemoryTracking=summary and jcmd VM.native_memory — breaks down where.

jcmd native memoryruns offline
# illustrative output
$ jcmd <pid> VM.native_memory summary
Total: reserved=3.1GB, committed=1.6GB
-   Java Heap       committed=1.0GB      (flat)
-   Thread          committed=0.1GB
-   Internal / Other (direct buffers)  committed=0.4GB   (climbing)

The gRPC exporter with a slow collector can hold direct buffers for in-flight batches, and an exporter timeout of 30 seconds with retries means many batches in flight at once.

The other candidate is a heap dump taken at hour eight, which shows what is actually retained; if it is not spans, the tracing change was a coincidence and the leak is something else that happened the same week.

Q118 · Scenario. "One Kafka broker's disk filled up. Within a minute, services across the platform that have nothing to do with each other started timing out on their API calls. Connect the dots."

Reveal answer

Strong answer A full disk makes a broker unable to accept writes for the partitions it leads; producers writing to those partitions block.

The chain to the API calls has two links:

  • Request path: a producer's send() blocks when its buffer is full, up to max.block.ms (60 seconds by default). If that send is called on a request thread, the thread is held for the whole block.
  • Outbox relay: if the outbox poller runs inside a transaction holding a database connection, the connection is held for the whole block.

The outbox relay and any code that publishes on the request path are the two places this happens.

Evidence: the broker's disk alert, the producer metrics (buffer available bytes, record error rate), thread dumps showing threads in KafkaProducer.send or the poller holding connections, and the connection pool's wait time.

Causes ranked:

  1. request-path publishing with a long max.block.ms;
  2. the outbox poller holding a database transaction across the Kafka send, so blocked sends exhaust the connection pool and unrelated queries queue behind them;
  3. a single broker leading many partitions with a replication factor that lets it be the only in-sync replica.

Fix:

  1. free the disk (retention, or add capacity) and let the cluster recover;
  2. set max.block.ms to a few seconds and treat it as a failure;
  3. publish only from the outbox relay, never on the request path;
  4. have the relay send outside the transaction and mark rows in a short transaction afterwards;
  5. ensure replication factor 3 with min.insync.replicas=2 so one broker's loss is absorbed.

Prevention: broker disk alerts at 70%, and a fault-injection test that pauses a broker.

Picture it A full disk on one broker turning into blocked request threads and an exhausted connection pool in services that never talk to each other (the relay is the outbox pattern).

The setup: Broker-2 leads a third of the partitions. Order, payment, inventory and notification all publish events. The order service has 200 request threads, a pool of 20 database connections and 300 requests per second, and each request publishes.

Make the invisible visible: Who is blocked on what.

topology and blast radiusruns offline
# illustrative output
   Order ----\                         broker-2 (disk 100 %)  leads 8 of 24 partitions  ✗ writes fail
   Payment ---+--> producers --------> broker-1 ✓   broker-3 ✓
   Inventory -/        send() blocks up to max.block.ms (60 s)
 blocked: request threads in send(), relay holding DB connections -> unrelated queries wait behind them

The trace: Occupancy at three moments.

order service occupancyruns offline
# illustrative output
t=0 s    threads busy 12 / 200   db pool 3 / 20 active   5xx 0.1 %    broker disk full
t=1 s    threads busy 200 / 200 (300 rps x 0.67 s fills 200 threads)   db pool 20 / 20, 140 waiting   5xx 35 %
t=60 s   max.block.ms expires: sends fail, threads free, queue drains   5xx falling
arithmetic: 200 threads / 300 rps = 0.67 s until every thread is parked in send()

What you see: A thread dump and the pool metrics.

thread dump excerptruns offline
# illustrative output
"http-nio-8080-exec-87" TIMED_WAITING (parking)
    at org.apache.kafka.clients.producer.internals.BufferPool.allocate(...)
    at org.apache.kafka.clients.producer.KafkaProducer.send(...)
hikaricp_connections_pending = 140     hikaricp_connections_active = 20

Why: Request threads and relay transactions waited on Kafka, so one broker's failure became a shared-resource failure.

The fix: A short max.block.ms, publish only from the relay, send outside the transaction, replication factor 3 with min.insync.replicas=2.

What you see now: The same broker failure after the fix.

order service occupancyruns offline
# illustrative output
t=1 s    threads busy 14 / 200    db pool 4 / 20    5xx 0.1 %   (events wait in the outbox table)
outbox unpublished rows: 0 -> 900 -> 5,400 over 3 min, drained after recovery
Symptom, root cause, action
SymptomRoot causeAction
Unrelated services time out togetherShared resource held while waiting on KafkaFail fast on send, publish from the relay
DB pool pending count rises, queries are slowRelay transaction spans the Kafka sendClaim, send outside the transaction, mark published
One broker failure hits many topicsOne broker leads many partitions, weak replicationRF 3, min.insync.replicas=2, split clusters at scale

Land it The broker was the root cause, but the blast radius came from threads and connections held while waiting on it — the platform's coupling to Kafka was tighter than anyone had drawn.

Likely follow-ups
"Show me the outbox relay code shape that holds the connection across the send, and the fixed shape."

The broken shape is a single @Transactional method: select unpublished rows with FOR UPDATE SKIP LOCKED, loop calling kafkaTemplate.send(...).get() for each, update them as published, commit.

OutboxRelay.javaruns offline
// ❌ TRAP: one transaction (and one DB connection) held across every Kafka send
@Transactional
void relay() {
    for (OutboxRow r : repo.selectUnpublishedForUpdateSkipLocked(100)) {
        kafka.send(r.topic(), r.key(), r.payload()).get();   // may block for max.block.ms
        r.markPublished();
    }
}
// ✅ FIX: short claim, send with no transaction, short mark
List<OutboxRow> batch = tx.execute(s -> repo.claim(100, claimToken));        // commit
List<Result> sent = sendAll(batch, Duration.ofSeconds(5));                   // no transaction
tx.executeWithoutResult(s -> repo.markPublished(idsOf(sent)));                // commit
// Result: connections held for milliseconds; a sweeper reclaims stale claims

The transaction — and its database connection — is held for the entire loop, so a send that blocks for max.block.ms holds the connection for sixty seconds, and with several relay threads the pool is exhausted.

The fixed shape is three steps with no transaction across the send: a short transaction that selects a batch and marks it claimed_at = now() with a claim token, commit; then the sends, outside any transaction, collecting the futures and waiting with a bounded timeout; then a second short transaction that sets published_at for the ids that succeeded.

Rows claimed but not published are reclaimed by a sweeper after the claim age exceeds a minute, which handles a crash between steps, and the consumer's idempotency handles the duplicate that produces. Connections are held for milliseconds.

"What do max.block.ms, delivery.timeout.ms, and request.timeout.ms each control?"

They govern three different waits in the producer. max.block.ms, default 60 seconds, is how long send() itself blocks the calling thread — waiting for metadata or for space in the buffer — before throwing; it is the one that parks request threads.

Producer timeouts
SettingDefaultWhat it controlsIn this incident
max.block.ms60 sHow long send() blocks the calling thread (metadata, buffer space)Parked request threads
delivery.timeout.ms120 sTotal time from send() to acknowledgement or failure, retries includedWhat the future waits on
request.timeout.ms30 sOne request to a broker before the producer retriesNot the cause

delivery.timeout.ms, default 120 seconds, is the total time from send() returning to the record being acknowledged or failed, including retries and time in the buffer; it is what the future's completion waits on.

request.timeout.ms, default 30 seconds, is the time for one request to a broker to be answered before the producer retries. In this incident the damage came from the first: threads stuck in send() for a minute.

I set max.block.ms to 2 to 5 seconds so a producer that cannot buffer fails fast, keep delivery.timeout.ms long enough to ride out a leader election — 30 to 60 seconds — and leave request.timeout.ms at its default. The outbox row is what makes failing fast safe.

"Why did one broker's disk affect so many partitions? Isn't that what replication is for?"

Replication protects against a broker being gone; it does not automatically protect against a broker being present but unable to write.

When a broker's disk fills, it does not immediately leave the cluster; it starts failing writes for the partitions it leads, and with acks=all the producer waits for that broker as a member of the in-sync set until it is removed from it, which takes time.

Once the broker's log directory is marked offline, it drops leadership and the controller elects new leaders from the replicas, and things recover — but that transition took the minute in which everything queued.

The second factor is how many partitions the broker led: with a small cluster and many topics, one broker can lead a third of all partitions, so one broker's trouble is a third of the platform's topics.

Replication factor 3 and min.insync.replicas=2 mean the write can proceed with two healthy replicas once the sick one is out of the set. The disk alert at 70% is what prevents the transition from ever being needed.

"What breaks at ten times the scale?"

At ten times the scale the coupling to Kafka becomes structural rather than incidental.

A single cluster shared by every service is one failure domain for the whole platform, and a broker problem — disk, a leader election storm, a version upgrade — is a platform-wide incident regardless of how well each producer is configured.

So at that scale I would split clusters by domain or by criticality, so that the checkout topics live on a cluster that a marketing-events topic cannot fill up, with MirrorMaker for the few topics that cross.

Producer-side, ten times the message rate means the buffer of buffer.memory fills in a fraction of the time during a stall, so the fail-fast setting matters more. Consumer-side, ten times the lag during a stall takes ten times as long to drain unless consumers have headroom.

And the outbox tables fill faster, which brings back the earlier question about the outbox poller's query plan on a table with millions of unpublished rows.

Q119 · Scenario. "After the mesh was upgraded and strict mTLS turned on, p99 latency rose by 40 milliseconds across the board and a few services show periodic 200-millisecond stalls. Diagnose."

Reveal answer

Strong answer Two symptoms, two causes.

  1. The uniform 40-millisecond rise: the proxy hop cost plus TLS. Every call now goes through a sidecar on each side, and if the sidecars are CPU-limited, they queue.
  2. The periodic 200-millisecond stalls: TLS handshakes.

Evidence for the first:

  • the sidecar container's CPU throttling metrics (Kubernetes CPU limits cause throttling well below 100% average usage);
  • the mesh's own per-hop latency.

The handshakes happen when:

  • connections are not being reused (a client that opens a new connection per request, or a keep-alive shorter than the request interval), so every request pays a full mTLS handshake;
  • certificate rotation causes brief re-handshakes across the fleet at the same moment.

Evidence: the connection-open rate on the proxies, and whether stalls align with the certificate rotation interval.

Causes ranked:

  1. sidecar CPU limits too low for the traffic;
  2. no connection pooling on clients (Spring's RestClient with the default JDK client pools connections, but a custom client factory may not);
  3. a very short certificate lifetime causing rotations to stack.

Fix:

  1. raise or remove sidecar CPU limits and set requests correctly;
  2. enable connection reuse and a keep-alive above the typical request gap;
  3. consider Istio's ambient mode, which removes the per-pod sidecar and most of the hop cost.

Prevention: a latency baseline before and after any mesh change, judged like a canary.

Picture it The order to payment call before and after the mesh upgrade: the hop, a CPU-quota burst that adds 87 milliseconds, and a connection counter that shows nothing is reused (see the sidecar and mesh block).

The setup: The order service calls payment at 200 requests per second. Both pods now have an Istio sidecar with a 500 millicore CPU limit.

Make the invisible visible: The path and the numbers at three moments.

call path and numbersruns offline
# illustrative output
before: order app ---------------------------------------> payment app
after:  order app -> sidecar --mTLS--> sidecar -> payment app      (two extra hops)

                          before upgrade   after upgrade   after fix
p99 latency               85 ms            125 ms          88 ms
mesh cost (client sidecar minus server app)  2 ms   40 ms   3 ms
new connections / minute  4                12,000          4
sidecar throttled periods 0 %              18 %            <1 %

The trace: Why a limit hurts at 8% average CPU: a burst spends the quota in a few milliseconds and the proxy then waits for the next period.

CFS quota traceruns offline
limit 500m => quota 50 ms of CPU per 100 ms period; a burst of 200 requests needs 80 ms of CPU; 4 cores free
t=0 ms      burst arrives, 4 cores busy
t=12.5 ms   50 ms of quota used            ✗ proxy paused until the period ends
t=100 ms    new period, quota refilled
t=107.5 ms  remaining 30 ms done           (unthrottled it would finish at t=20 ms: +87.5 ms)
average CPU if this happens once a second: 80 ms / 1000 ms = 8 %

What you see: The throttling ratio and the connection counter.

metricsruns offline
# illustrative output
container_cpu_cfs_throttled_periods_total / container_cpu_cfs_periods_total   istio-proxy order-7f9: 0.18
envoy_cluster_upstream_cx_total{payment}   +12,000 per minute   (= 200 rps x 60 s: every request opened a connection)

Why: A CPU limit throttles bursts even when the average is low, and a client without a pool pays a full handshake per request.

The fix: A generous or absent sidecar CPU limit with a correct request, and a singleton HTTP client with a keep-alive above the request gap.

What you see now: The same two metrics after the fix.

metricsruns offline
# illustrative output
throttled periods ratio: 0.004      envoy_cluster_upstream_cx_total{payment}: +4 per minute      p99 88 ms
Symptom, root cause, action
SymptomRoot causeAction
Uniform +40 ms p99Throttled sidecar and two extra hopsRaise or drop the CPU limit, set the request
Periodic 200 ms stallsNew connection per request, or rotation stormsSingleton client, keep-alive above the request gap
Cannot tell mesh from appNo per-hop viewCompare client sidecar and server app timings, or trace the hops

Land it The mesh adds a hop and a handshake, and both are cheap only when the proxy has CPU and the connection is reused — neither is true by default.

Likely follow-ups
"Explain CPU throttling on a sidecar — why does a limit hurt at 40% average usage?"

A Kubernetes CPU limit is enforced by the Linux CFS bandwidth controller in periods of 100 milliseconds by default.

A limit of 500 millicores means the container may use 50 milliseconds of CPU time in each 100-millisecond period; once it has used them, it is paused until the next period, even if the node has idle cores.

A proxy that is bursty is idle, then gets a burst of requests that needs three cores for five milliseconds.

It burns its quota in that burst and is throttled for the rest of the period.

That appears as tens of milliseconds of added latency on every request that arrived during the pause, while the average usage over a minute looks like 40%.

The metric that shows it is container_cpu_cfs_throttled_periods_total divided by container_cpu_cfs_periods_total; anything above a few percent is hurting latency. The fix is to set a CPU request for scheduling and either remove the limit or set it several times higher than the request.

pod annotationsruns offline
metadata:
  annotations:
    sidecar.istio.io/proxyCPU: "200m"       # request: what the scheduler reserves
    sidecar.istio.io/proxyCPULimit: "2"     # ✅ FIX: generous limit (the TRAP is a limit near the request)

Istio's default sidecar limit is 2 cores and its request is 100 millicores, which is fine unless someone lowered it.

"How do you separate the mesh's cost from the application's in the latency numbers?"

The mesh reports its own view. Istio's proxy emits istio_request_duration_milliseconds from both the client sidecar and the server sidecar, tagged with the source and destination workloads; the application's own timer measures from the moment the request reaches the servlet.

The difference between the client sidecar's measurement and the server application's is the two proxy hops plus the network. Before and after the upgrade, that difference is the number: if it went from 2 milliseconds to 40, the mesh is the cost.

To go finer, the proxy's access log can include upstream-connect and response-flag fields — a UF or UC flag points at connection problems, and a large gap between downstream and upstream timings is the proxy itself.

And a trace with the sidecars instrumented as spans shows each hop explicitly; Istio can emit those spans when tracing is enabled on the proxy. I would compare a trace from before the upgrade with one after, hop by hop.

"What does connection reuse look like on the client side in Spring, and how do you verify it?"

Spring's RestClient built on the JDK HttpClient keeps a connection pool by default, with keep-alive governed by jdk.httpclient.keepalive.timeout, which defaults to 30 seconds; with Apache HttpClient 5 it is a PoolingHttpClientConnectionManager with a configurable time-to-live and idle eviction.

The failure mode is creating a new client per request — a RestClient.create() inside a method — which creates a new pool each time and never reuses anything; the client must be a singleton bean.

PaymentClientConfig.javaruns offline
// ❌ TRAP: a new client, and a new pool, on every call
String callBad() { return RestClient.create().get().uri("http://payment/charges").retrieve().body(String.class); }
// ✅ FIX: one client bean, one pool
@Bean RestClient paymentClient(RestClient.Builder b) { return b.baseUrl("http://payment").build(); }

With a mesh, the application's connections go to the local sidecar, which keeps its own pool to the destination, so both pools matter, and Istio's DestinationRule connection pool settings govern the second.

Verification is a count: the sidecar's envoy_cluster_upstream_cx_total for the destination should grow slowly, roughly at the rate connections expire, not at the request rate. If it grows at the request rate, nothing is being reused.

"Is ambient mode actually faster, and what does it give up?"

It removes the per-pod sidecar and replaces it with a per-node layer-4 proxy — ztunnel — that handles mTLS and identity, with an optional per-namespace layer-7 waypoint proxy for HTTP policy.

Traffic that only needs mTLS goes through ztunnel, which is a single lightweight hop with no HTTP parsing, and in Istio's own numbers the added latency is a fraction of the sidecar's and the CPU cost is much lower because there is one proxy per node rather than per pod.

What it gives up: layer-7 features — retries, header-based routing, HTTP metrics — need a waypoint, which reintroduces a hop for those namespaces; per-pod isolation of the proxy is gone, so one noisy workload can affect its node's neighbours through the shared ztunnel; and as of Aug 2026 it is stable in Istio but some integrations and observability tools still assume sidecars.

I would move the latency-sensitive services that need only mTLS to ambient first and measure, rather than switch the whole platform at once.

Q120 · Scenario. "Finance says the warehouse's daily order total is consistently 0.8% lower than the order service's own total, and the gap started three weeks ago. Where do you look?"

Reveal answer

Strong answer A consistent percentage gap that began on a date is a class of events being dropped or misread since a change.

Evidence: the deploys three weeks ago on the order service and the warehouse pipeline; the schema registry's version history for the order event; and a reconciliation of one day's orders by id between the two systems to see which orders are missing, and what they have in common.

Causes ranked:

  1. Filter not updated: a new order type or status (a split shipment or a marketplace order) introduced three weeks ago that the warehouse's projection does not count, because it filters on a status list that was not updated.
  2. Intolerant consumer: an event schema change with a new enum value that the warehouse consumer, not being a tolerant reader, sends to its dead-letter topic silently.
  3. Unconsumed partition: a partition or consumer group change that left one partition unconsumed by the warehouse for that period, which would show as missing orders clustered by key hash.
  4. Money format: a currency or rounding change.

Fix:

  1. find the missing orders' shared attribute;
  2. correct the projection or consumer;
  3. replay the three weeks from the topic into the warehouse, which is the value of keeping retention long.

Prevention: a daily automated reconciliation between source-of-truth counts and every derived store, alerting on drift, and a dead-letter topic that is monitored rather than merely present.

Picture it One day of orders compared row by row between the order service and the warehouse, the dead-letter topic growing for three weeks, and what the shape of the gap tells you (see the dead-letter block).

The setup: The order service creates 48,000 orders a day. The warehouse builds its own copy from the OrderPlaced and later events.

Make the invisible visible: The rows of both stores for the same day.

orders versus wh_ordersruns offline
# illustrative output
order service orders                       warehouse wh_orders
o-5001 PAID            web          49.00  o-5001 PAID   49.00     ✓
o-5002 PAID            web          12.50  o-5002 PAID   12.50     ✓
o-5003 SPLIT_SHIPMENT  marketplace  80.00  (missing)               ✗ event rejected, sits in orders.events.DLT
counts for the day: source 48,000   warehouse 47,616   missing 384  = 0.8 %

The trace: The dead-letter topic at three moments. Each missing order emits about five events, so 384 orders a day is about 1,920 messages a day.

dead-letter topic sizeruns offline
# illustrative output
day 1    1,920 messages    (384 orders x 5 events)      no alert
day 7   13,440 messages
day 21  40,320 messages     ~ the 40,000 nobody knew about

What you see: The reconciliation output of the diagnosis.

reconcile one dayruns offline
# illustrative output
in both, totals match     47,616
in both, totals differ         0
in source only               384   all status=SPLIT_SHIPMENT, channel=marketplace, created after 2026-10-25

Why: The consumer treated a value it had not seen before as a poison record, and nobody owned the dead-letter topic.

The fix: Map unknown values to UNKNOWN and count them, fix the projection, replay the dead-letter topic, and reconcile daily.

What you see now: The same reconciliation after the replay.

reconcile one dayruns offline
# illustrative output
in source only                 0       unknown status values seen today: 12 (counted, alert raised)
replay arithmetic: 40,320 messages at 1,000 per second = ~40 s
Shape of the gap, root cause, action
Shape of the gapRoot causeAction
Missing orders share a status, channel or currencyFilter or schema issueFix the mapping, replay the dead-letter topic
Missing orders spread uniformlyPartition or consumer problemCheck group assignment and lag per partition
Missing orders keyed to a partition rangeOne partition unconsumedFix the consumer and replay
Dead-letter topic growing, no alertNo ownerRate alert, named owner, weekly review

Land it Derived data drifts silently, and the only defence is a reconciliation that compares it to the source every day and shouts when it differs.

Likely follow-ups
"How do you do the reconciliation for one day quickly, without a data engineer?"

With two exports and a join. From the order service's database I export the ids and totals of orders created on one day — a single query to CSV — and from the warehouse I export the same for the same day.

reconcile.sqlruns offline
-- order service: one day to CSV
SELECT id, total FROM orders WHERE created_at >= DATE '2026-11-14' AND created_at < DATE '2026-11-15';
-- warehouse: same query on wh_orders, then load both exports into a scratch schema
SELECT o.id, o.status, o.channel
FROM src_orders o LEFT JOIN wh_orders w ON w.id = o.id
WHERE w.id IS NULL;     -- the 0.8 %: look at what these rows share

A join on order id in either database, a spreadsheet, or a short script gives three sets: in both with matching totals, in both with different totals, and in the source but not the warehouse.

The last set is the 0.8%, and the very next step is to look at what those orders share: a status, a channel, a currency, a creation hour, a partition key range. In practice one column explains it within an hour.

If the missing orders are spread uniformly, that points at a partition or a consumer issue; if they cluster on an attribute, it is a filter or a schema issue.

A day is small enough — tens of thousands of rows — that no pipeline is needed for the diagnosis; the automated daily version comes after.

"The dead-letter topic had 40,000 messages in it and nobody knew. How should it have been monitored?"

A dead-letter topic is an error queue, and its size is an error count.

The minimum is a metric of messages produced to each dead-letter topic per minute, alerting on any nonzero rate sustained for five minutes, routed to the owning team — that catches the first day of drift.

Better is a lag-style metric: the number of messages in the dead-letter topic that have not been reprocessed, with a dashboard panel on the service's default page.

The 40,000 with no alert means the topic existed as a place to put failures but nobody was assigned to it, which is the organisational half: every dead-letter topic has a named owner, a runbook for triage, and a weekly review until it is empty.

Tooling-wise, a small dead-letter service that consumes those topics, groups the messages by exception type, and shows counts per type in one place turns forty topics into one view, and lets an engineer replay a group after a fix with one action.

"How would the warehouse consumer have handled the new enum value safely?"

By being a tolerant reader with an explicit unknown bucket, and by counting what it did not understand.

OrderStatus.javaruns offline
public enum OrderStatus {
    NEW, PAID, SHIPPED,
    @JsonEnumDefaultValue UNKNOWN   // ✅ FIX: unknown values still count; they are flagged, not dropped
}
// needs DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE enabled on the ObjectMapper
// ❌ TRAP without it: the consumer throws and the record goes to the dead-letter topic

In the deserialiser, an unknown enum value maps to UNKNOWN rather than throwing — Jackson's @JsonEnumDefaultValue — and the projection's rule is that an order with an unknown status is still an order: it is counted in totals and flagged in a status column, not dropped and not dead-lettered.

A metric counts unknown values per field, and an alert on it fires the day the producer adds a new one, so the warehouse team updates its mapping within days instead of discovering a three-week gap.

The design principle is that a consumer's ignorance should be visible and non-destructive: it should never silently exclude data, and it should never block on data it does not understand. Dead-lettering is for records that are malformed, not for records that are merely new.

"Design the automated daily reconciliation so it does not become another thing nobody looks at."

It runs as a scheduled job in the warehouse pipeline at 06:00, after the previous day's data has settled, and it compares three numbers per derived store against the source of truth: the count of orders, the sum of totals, and the count by status, for the previous day.

The output is a metric per store — the relative difference — and an alert at 0.1% that goes to the owning team's channel with a link to the list of mismatched ids, which the job also writes to a table.

The important design choices are that the alert names the specific orders, so the response is investigation rather than a shrug; that the threshold is tight enough to catch drift on day one; and that a job that fails to run is itself alerted through the "time since last successful run" metric from the scheduled-jobs question.

The reconciliation for money — order totals versus payment ledger — is the same job with a zero tolerance and finance on the alert.

Q121 · Scenario. "The payment service was moved to a new cluster and its DNS name now resolves to new addresses. Most callers followed within a minute, but the order service kept calling the old, dead addresses for over an hour until restarted. Why?"

Reveal answer

Strong answer The order service cached the DNS answer and never asked again. Evidence: the JVM's DNS cache settings (networkaddress.cache.ttl in the security properties), the HTTP client's connection pool behaviour, and the base image's configuration.

The mechanism has two parts that each remember the old address:

  • The JVM DNS cache: the JVM caches successful DNS lookups, by default for 30 seconds in current JDKs, but "forever" when the property is set that way in an inherited base image or when a security manager was enabled in older setups.
  • The connection pool: an HTTP client with a connection pool keeps established connections to the old addresses open and reuses them as long as they answer. If the old endpoints half-work (accept the connection, then fail), the pool never evicts them.

Causes ranked:

  1. an infinite JVM DNS TTL from the base image's java.security;
  2. connection pooling with no maximum connection lifetime;
  3. clients resolving once at startup and holding the addresses.

Fix:

  1. set networkaddress.cache.ttl to 30 seconds or less in the base image;
  2. set a maximum connection age on the HTTP client pool so connections are recycled every few minutes;
  3. in Kubernetes, use the Service's stable virtual IP rather than resolving pods directly.

Prevention: a base-image check for the DNS TTL setting, and a runbook step that any endpoint move is followed by verifying callers' connection targets rather than assuming DNS propagation.

Picture it The order service's view of the payment address at three moments after the move, and why it stays wrong for an hour (see service discovery).

The setup: Payment moves to a new cluster. Its DNS name now points at 10.8.0.20 instead of 10.1.0.5. The order service sends 200 requests per second through a pool of 20 connections.

Make the invisible visible: What the order service remembers, at three moments.

order service stateruns offline
# illustrative output
                         t=0 (DNS flips)    t=1 min                 t=60 min
DNS name resolves to     10.8.0.20          10.8.0.20               10.8.0.20
JVM cache in order       10.1.0.5 (ttl -1)  10.1.0.5 (never expires)  10.1.0.5
pooled connections       20 -> 10.1.0.5     20 -> 10.1.0.5 (accepted, then fail)  same
calls to payment failing 0 %                100 % (other callers 0 %)  100 %

The trace: Two layers, each with its own lifetime.

lookup and connectionruns offline
order app -> InetAddress cache: payment -> 10.1.0.5 (cached, ttl -1)     ✗ never asks DNS again
order app -> pool: connection #7 to 10.1.0.5 still open, peer answers       ✗ never evicted
restart  -> cache empty, pool empty -> DNS -> 10.8.0.20                      ✓

What you see: The setting in the base image.

consoleruns offline
# illustrative output
$ grep -n '^networkaddress.cache.ttl' $JAVA_HOME/conf/security/java.security
132:networkaddress.cache.ttl=-1

Why: Neither the cache nor the pool had a lifetime, so the address was remembered until restart.

The fix: A TTL of 30 seconds or less in the base image and a maximum connection age of a few minutes.

What you see now: Staleness is bounded by both lifetimes.

worst caseruns offline
DNS ttl 30 s + connection time-to-live 2 min  ->  the order service follows the move within about 2.5 minutes
(a connection opened at minute 1:59 resolves through a cache at most 30 s old)
Symptom, root cause, action
SymptomRoot causeAction
One caller keeps hitting old addressesInfinite JVM DNS TTLnetworkaddress.cache.ttl in the security file
Fresh DNS but still failingPooled connections never recycledTime-to-live on the pool, maxConnectionDuration on the mesh
Old address half-worksEndpoint accepts then failsClose old endpoints actively (reset), recycle by age

Land it DNS propagation is not the whole story — the JVM's cache and the connection pool each remember the old address, and both need a lifetime.

Likely follow-ups
"Where exactly is the JVM DNS TTL configured, and what are the defaults as of Aug 2026?"

It is the security property networkaddress.cache.ttl in $JAVA_HOME/conf/security/java.security, or set programmatically with java.security.Security.setProperty("networkaddress.cache.ttl", "30") before any lookup, and the companion networkaddress.cache.negative.ttl for failed lookups, default 10 seconds.

DnsSetup.javaruns offline
// ❌ TRAP: -Dnetworkaddress.cache.ttl=30 does nothing, it is a security property, not a system property
// ✅ FIX: set it before the first lookup (or in java.security)
java.security.Security.setProperty("networkaddress.cache.ttl", "30");

In current JDKs — 17, 21, and 25 — the default for successful lookups when no security manager is installed is 30 seconds, and the property is commented out in the shipped file.

The "cache forever" behaviour came from the days when a security manager was present, and it persists in base images where someone set the property to -1 explicitly, often to work around a DNS outage years ago.

Note that it is not a system property, so -Dnetworkaddress.cache.ttl does nothing, which is a classic trap; it has to be in the security file or set through the Security class.

I would check the running value with a tiny script in the actuator or by reading the file in the image.

"How do you set a maximum connection lifetime on the HTTP client pool, and what value?"

With Apache HttpClient 5, PoolingHttpClientConnectionManagerBuilder.create().setDefaultConnectionConfig(ConnectionConfig.custom().setTimeToLive(TimeValue.ofMinutes(2)).build()) closes any connection older than two minutes regardless of activity, and setValidateAfterInactivity checks a connection that has sat idle before reusing it.

PoolConfig.javaruns offline
var cm = PoolingHttpClientConnectionManagerBuilder.create()
    .setDefaultConnectionConfig(ConnectionConfig.custom()
        .setTimeToLive(TimeValue.ofMinutes(2))   // ✅ FIX: recycle by age, not by failure
        .build())
    .build();

With the JDK HttpClient there is no per-connection lifetime setting, only the keep-alive idle timeout, so connections that stay busy live forever — one reason to prefer Apache or Reactor Netty for service clients. Reactor Netty's ConnectionProvider has maxLifeTime.

Two minutes is a good default: long enough that connection setup is amortised over hundreds of requests, short enough that an endpoint move is followed within minutes.

With a mesh, the sidecar's upstream pool needs the same setting — Istio's DestinationRule has maxConnectionDuration — because the application's connection to the sidecar is not the one that matters.

"Why did the old addresses still accept connections if the service had moved?"

Because moving a service rarely turns off the old infrastructure immediately.

The old cluster's load balancer or pods may have stayed up for a grace period, accepting connections and then failing because the backend was gone or draining — and a pool sees an accepted connection as healthy.

Or the addresses were reassigned to something else that listens on the port. A pool with no health validation keeps a connection until the peer closes it, and a peer that accepts and then times out never closes it cleanly.

That is why the recycling has to be by age, not by failure.

It also points to a runbook gap: an endpoint move should include shutting down the old endpoint in a way that actively closes connections — a TCP reset, not a silent drop — so that pooled clients are forced to reconnect and resolve again.

In Kubernetes, deleting the old Service removes the virtual IP and the kernel resets connections to it, which is the cleanest cut.

"In Kubernetes with a Service virtual IP, does any of this still apply?"

Less, but not nothing.

Inside one cluster a client resolves the Service name to a stable cluster IP, and kube-proxy or the CNI rewrites connections to whichever pod is currently an endpoint, so a pod move is invisible to the client's DNS cache — the IP did not change.

What still applies is established connections: an existing TCP connection is pinned to the pod it was rewritten to, and if that pod dies the connection breaks, which is fine, but if the pod is merely removed from endpoints while still alive, the connection keeps going to it.

So connection lifetime still matters. And across clusters — the scenario here — the client resolves an external name to a load balancer address, and the DNS cache and pool lifetime are exactly as relevant as on any other network.

Headless Services, which return pod IPs directly, put the whole problem back on the client, which is why I avoid them for HTTP clients.

Q122 · Scenario. "About 2% of service-to-service calls fail with 'token not yet valid' errors, only from pods on three particular nodes. Explain, and connect it to the Distributed Systems primer."

Reveal answer

Strong answer "Not yet valid" means the token's not-before time, set by the issuer's clock, is later than the current time on the validating pod — so the three nodes' clocks are behind the issuer's by more than the tolerance.

Evidence: the node clock offsets (chronyc tracking on each node), the tokens' nbf and iat claims compared with the validators' wall time, and whether the failures cluster on tokens issued in the last second or two.

Causes ranked:

  1. time synchronisation broken or misconfigured on those nodes: an NTP daemon not running after a node image change, or a node blocked from reaching the time source;
  2. a virtual-machine clock drift after live migration;
  3. a validator with zero clock-skew tolerance.

Fix:

  1. repair time synchronisation on the nodes and add a node-level alert on clock offset;
  2. set a clock-skew tolerance of 30 to 60 seconds in the token validators (Spring Security's JWT decoder supports this);
  3. avoid setting nbf to the exact issue time.

The connection to the Distributed Systems primer: no two machines agree on the time.

  • Every protocol that compares timestamps across machines needs a tolerance.
  • It must not treat a wall-clock difference as an ordering.
  • That is why leases, token expiry, and distributed locks all carry a skew margin.

Prevention: clock offset as a standard node health metric, alerted before it reaches the tolerance.

Picture it A token issued by one clock and validated by another that is 78 seconds slow, which tokens fail, and why that comes to about 2% of calls.

The setup: The issuer stamps a token at 10:00:00 with nbf equal to that time and 15-minute expiry. The payment pod on node-17 has a clock that is 78 seconds slow. The validator tolerance is 60 seconds.

Make the invisible visible: The two clocks side by side for tokens of different ages.

clock lanesruns offline
# illustrative output
issuer clock   10:00:00   token nbf=10:00:00  exp=10:15:00
node-17 clock  09:58:42   (78 s slow)
token age  5 s:  node-17 sees 09:58:47 -> nbf is 73 s in the future, tolerance 60 s   ✗ "Jwt used before 10:00:00"
token age 18 s:  node-17 sees 09:59:00 -> nbf is 60 s in the future                   ✓ accepted
token age 60 s:  node-17 sees 09:59:42 -> nbf is 18 s in the future                   ✓ accepted

The trace: How the failure share follows the offset.

Clock offset and failing share (900-second tokens, tolerance 60 s)
OffsetTokens younger thanShare of calls failing
12 snone0%
78 s18 s2% (18 / 900)
120 s60 s6.7% (60 / 900)

What you see: The offset on a bad node.

consoleruns offline
# illustrative output
$ chronyc tracking          (on node-17)
System time     : 78.123456789 seconds slow of NTP time
Leap status     : Not synchronised

Why: The node stopped synchronising after an image change, drifted, and then crossed the validator's tolerance.

The fix: Repair synchronisation, alert on offset, keep the tolerance as the last line.

What you see now: The same node after the fix.

consoleruns offline
# illustrative output
$ chronyc tracking          (on node-17)
System time     : 0.000041213 seconds fast of NTP time
Leap status     : Normal
token errors: 0 per minute
Symptom, root cause, action
SymptomRoot causeAction
Not yet valid on fresh tokens onlyValidator clock behind the issuerFix time sync on the node
Only pods on three nodesThose nodes differ (image, subnet, instance type)Compare node labels, images, subnets
Failures at any driftZero toleranceSkew tolerance of 30 to 60 seconds

Land it Any check that compares a timestamp across two machines is a distributed-systems problem, and it needs a skew tolerance and a monitored clock or it will fail on three nodes at 2%.

Likely follow-ups
"How do you set the clock-skew tolerance in Spring Security, and why not make it five minutes?"

The decoder's validator takes it: NimbusJwtDecoder with setJwtValidator(new DelegatingOAuth2TokenValidator<>(new JwtTimestampValidator(Duration.ofSeconds(60)), new JwtIssuerValidator(issuer))), where the timestamp validator's argument is the allowed skew applied to both nbf and exp.

JwtConfig.javaruns offline
OAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<>(
    new JwtTimestampValidator(Duration.ofSeconds(60)),   // skew tolerance applied to nbf and exp
    new JwtIssuerValidator(issuer));
decoder.setJwtValidator(validator);

The default is 60 seconds, so if these failures happened with the default, the nodes were more than a minute out, which is a badly broken clock, not drift.

Making it five minutes would mask that, and it widens the window in which an expired token is still accepted, which for a fifteen-minute token is a third of its lifetime.

The tolerance should be a small multiple of the worst clock error you are willing to run with — I want nodes within a second and I alert at ten, so 60 seconds of tolerance is generous — and the real fix is the clocks, with the tolerance as the margin, not the other way round.

"Why only three nodes? What would make time sync break on some nodes and not others?"

The usual answer is that those three are different in some way that nobody labelled.

Typical differences:

  • they came from a newer node image where chrony was not enabled in the image's systemd defaults;
  • they sit in a subnet whose egress rule blocks UDP 123 to the time source;
  • they are a different instance family where the hypervisor's clock source behaves differently after a live migration;
  • they were the ones that rebooted after a change to the NTP configuration that the others had not picked up yet.

chronyc tracking on a bad node shows a large offset and, in the sources list, whether it can reach any server at all.

I would compare the node labels, image versions, and subnets of the three against the rest — the discriminating attribute is usually visible in kubectl get nodes -o wide or the cloud console.

Then the fix is to make the node health check include clock offset so a node that drifts is cordoned before pods land on it.

"The primer says wall clocks cannot be used for ordering. So how does anything with expiry work?"

By treating time as approximate and building the error into the protocol. Token expiry works because both sides accept a skew tolerance and because a token that is accepted a minute late does little harm.

Leases — the mechanism behind distributed locks and leader election — work because the holder assumes its lease ended earlier than the wall clock says, by the maximum skew plus the maximum pause, and the granter assumes it ended later; the gap between those two views is time in which nobody claims the resource, which is safe.

Where a strict ordering across machines is needed, wall clocks are replaced: a monotonic sequence from a single writer, a fencing token from the lock service that increases on every grant, or a logical clock.

The rule is that a wall clock may decide "roughly when" and never "which came first", and every one of those mechanisms — leases, tokens, TTLs — carries a margin sized to the clock error the operators promise to keep.

"What is the alert, and how do you make sure a drifting node never takes traffic?"

The node exporter for Prometheus exposes node_timex_offset_seconds and node_timex_sync_status. The alert is the absolute offset above 0.5 seconds for five minutes, or sync status zero for ten minutes, per node, to the platform team.

To keep a drifting node from taking traffic, I turn the alert into an action: a small controller — or a rule in the node problem detector, which Kubernetes supports for exactly this kind of condition — sets a node condition ClockSkew=True when the offset crosses the threshold, and a taint that stops new pods scheduling there; pods already running are left alone unless the offset is severe, because evicting for a clock is worse than serving with a tolerance.

A weekly report of maximum offset per node catches slow degradation. And the token validators on every service keep their 60-second tolerance as the last line, so a node that drifts for a minute before the taint applies does not cause 2% errors.

Q123 · Scenario. "A partner integration gets rate-limited every night at exactly midnight UTC, receives 429s for two minutes, and their retries make it worse. The limit is 1,000 requests per minute per API key, and their traffic is 400 per minute. Why?"

Reveal answer

Strong answer The partner is under their limit on average and over it at one instant, which points at a burst plus a limiter that counts in fixed windows.

Evidence: the partner's request timestamps around midnight (they likely run a batch that fires several hundred requests in the first seconds of the day), the limiter's algorithm and window alignment, and whether the limiter's counters are per gateway instance or shared.

Causes ranked:

  1. Fixed window: a fixed-window counter aligned to the clock minute, so a burst at 00:00:00 plus normal traffic exceeds 1,000 in that single window even though the hourly rate is fine.
  2. Per-instance counters: counters kept per gateway instance with a client whose requests happen to concentrate on one instance, so that instance's local count trips early.
  3. Retries without backoff: the partner's retries keep the window full.

Fix:

  1. switch to a sliding-window or token-bucket limiter with a burst allowance (a bucket of 1,000 tokens refilled at 1,000 per minute lets a burst through and then throttles smoothly);
  2. keep counters in a shared store (Redis with atomic increments, or a mesh-level global limiter) so the limit applies to the key, not to the instance it hit;
  3. return Retry-After so the partner's client backs off properly;
  4. talk to the partner about spreading the batch with jitter.

Prevention: limiter behaviour documented with the algorithm named, and burst tests as part of the gateway's test suite.

Picture it The partner's midnight batch counted by a fixed window, by per-instance counters and by a token bucket, with the counts at three moments (see rate limiting).

The setup: The partner's key allows 1,000 requests per minute. Their steady traffic is 400 per minute, and a midnight batch of 1,300 requests starts at 00:00:00 (700 in the first ten seconds). The gateway has 12 instances.

Make the invisible visible: The fixed-window counter for three consecutive minutes.

fixed-window countsruns offline
# illustrative output
window       normal  batch  retries  attempted  admitted  429s
00:00-00:59    400    700      0       1,100      1,000    100   (trips at request 1,001)
00:01-01:59    400    600    100       1,100      1,000    100   (batch tail plus retries)
00:02-02:59    400      0    100         500        500      0   -> about two minutes of 429s

The trace: The same traffic through a token bucket of 1,000 tokens refilled at 1,000 per minute (16.7 per second), and through local limits of 1,000 / 12 = 83 per instance.

token bucket and per-instanceruns offline
token bucket
00:00:00  1,000 tokens (full)      batch of 700 admitted ✓  -> 300 left
00:00:10  300 + 16.7 x 10 refill - 6.7 x 10 normal = 400 tokens
steady 400/min = 6.7 per s, below the 16.7 per s refill, so the bucket always recovers: 0 x 429

per-instance limit 83 per minute, batch on one connection landing on gw-4
requests 1..83 ✓   requests 84..700 ✗ 429  (617 rejected)    the other 11 instances see ~0 for this key

What you see: The response the partner receives.

HTTP responseruns offline
HTTP/1.1 429 Too Many Requests
Retry-After: 12
# a client that ignores Retry-After retries at once and keeps the window full

Why: The partner is under the limit on average and over it in one aligned window, and a local counter turns the limit into 83 per connection.

The fix: A shared token bucket with a burst allowance, and Retry-After honoured by the client.

What you see now: The same midnight with the bucket.

token bucketruns offline
# illustrative output
00:00-02:59   attempted 3,300   admitted 3,300   429s 0     lowest bucket level 300 tokens
Symptom, root cause, action
SymptomRoot causeAction
429s for two minutes at midnight, normal rate below limitFixed window aligned to the clockToken bucket or sliding window
Rejections from one gateway instance onlyPer-instance countersShared counter (Redis or global limit service)
Rejections go on after the batch is overRetries without backoffRetry-After, jitter on the partner side

Land it A rate limit is a promise about a window, and a fixed window aligned to the clock punishes anyone whose cron job runs on the minute — token buckets keep the promise and forgive the burst.

Likely follow-ups
"Explain the fixed-window edge case with numbers — how can 400 a minute exceed 1,000?"

The partner's midnight batch sends, say, 700 requests in the first ten seconds of the day, then their normal 400 a minute continues.

A fixed window aligned to the minute counts everything from 00:00:00 to 00:00:59: 700 from the batch plus roughly 400 from normal traffic is 1,100, and the limit trips at request 1,001, so the last 100 get 429s. That is the first minute.

Then the retries: those 100 clients retry immediately, and so do the next minute's normal 400, and the window for 00:01 fills with 400 normal plus 100 retries plus whatever else the batch has queued, and it keeps tripping until the batch drains, which is the two minutes.

The partner's monthly average is 400 a minute and entirely honest. A token bucket with capacity 1,000 and refill 1,000 a minute admits the 700-request burst from a full bucket, refills at 16.7 a second, and never rejects anyone at 400 a minute steady state.

"What if the per-instance counters are the cause rather than the algorithm — how do you tell?"

By looking at the counts per gateway instance at midnight.

If the limiter is local to each of twelve instances with a limit of 1,000 divided by twelve, about 83 per instance, and the partner's batch is coming through one persistent connection, that connection lands on one instance and 700 requests hit an 83-per-minute local limit — the rejections start at request 84.

The signature is that the rejections come from one instance while others report almost nothing for that key.

The fix is the shared counter in Redis, or, if the gateway is Envoy-based, the global rate limit service, so that the limit applies to the key across the fleet.

If the limiter is already shared and the algorithm is fixed-window, the rejections are spread across instances and start around request 1,001. The per-instance case is worse for the partner because it makes the effective limit depend on connection routing, which they cannot see or control.

"The partner says they cannot change their batch. Give them a solution."

Two options that need nothing from them. First, the token bucket: with the burst allowance their 700-request batch is admitted from the full bucket, which fixes it outright.

429 responseruns offline
HTTP/1.1 429 Too Many Requests
Retry-After: 12
# with the bucket the 700-request burst never sees this; a client that honours the header waits 12 s

Second, if I cannot change the algorithm quickly, I raise their key's burst limit for the first minutes of the day — a per-key configuration with a schedule — or give their batch traffic a separate key with its own limit, which is a one-line change in their configuration on our side.

What I ask of them in return is to honour Retry-After, which their client currently ignores, because that is what turns a two-minute rejection into a smooth queue instead of a storm; most HTTP client libraries do this with one setting.

And I give them the algorithm in writing: bucket size, refill rate, and the headers they will see, so the next integration is designed against the real behaviour rather than a number in a contract.

"What is the difference between a sliding window and a token bucket, and when would you choose the window?"

A sliding window counts requests in the last N seconds ending now — either exactly, by keeping timestamps in a sorted set, or approximately, by weighting the previous fixed window's count by how much of it overlaps.

It enforces "never more than N in any 60-second span", which is a strict statement with no burst allowance beyond the limit.

A token bucket enforces an average rate with a burst up to the bucket size, so short bursts above the rate are fine as long as the average holds.

The bucket is friendlier to real clients, which are bursty, and cheaper to store — two numbers per key.

The sliding window is the right choice when the limit is a hard protection for the backend — a database that genuinely cannot take more than N a minute — rather than a fairness rule for clients, because the bucket's burst would hurt the backend.

For partner API keys, the bucket; for a per-tenant limit protecting a shared database, the window.

Q124 · Scenario. "Inventory reservations stopped for three hours. The consumer was running, lag was growing on exactly one partition, and the same error appeared in the log every second. What happened and what should have been in place?"

Reveal answer

Strong answer One partition stuck with a repeating error is a poison message: a record the consumer cannot process, retried in place forever, blocking everything behind it on that partition while the other partitions flow.

Evidence: the offset that is not advancing, the record at that offset (its payload, headers, and producer), and the exception.

Causes ranked:

  1. a malformed or unexpected payload: a schema change without a compatible registry check, or a null in a field the consumer assumed present;
  2. a record referencing an entity that does not exist in inventory's database yet (an ordering problem across topics);
  3. a bug in a code path that only that record exercises.

Fix now: skip the record by seeking the consumer past it after copying it aside — Spring Kafka lets an error handler do this — and reprocess it after the bug is fixed.

What should have been in place:

  • an error handler with a bounded retry (say three attempts with backoff) that then publishes the record and its exception to a dead-letter topic and commits past it, so one bad record costs seconds rather than hours;
  • a distinction between transient errors (retry) and deterministic ones (dead-letter immediately);
  • an alert on any partition whose committed offset has not advanced for more than a minute while it has lag;
  • an owner for the dead-letter topic.

Prevention: schema-registry compatibility enforced in the producer's pipeline, and a consumer that validates and rejects rather than throwing halfway through.

Picture it Partition 7 of the order events topic stuck on one record for three hours, with lag at three moments, the retry timeline with and without a bound, and why the total-lag alert never fired (see the dead-letter block and the idempotent consumer for the replay).

The setup: The inventory consumer group reads 24 partitions at 600 messages per second in total, 25 per partition. The record at offset 881,402 of partition 7 cannot be processed.

Make the invisible visible: The consumer group's view of partition 7 at three moments.

consumer group lagruns offline
# illustrative output
PARTITION  CURRENT-OFFSET  LOG-END-OFFSET     LAG
t=0 h   7      881,402        881,403            1
t=1 h   7      881,402        971,403       90,001   (3,600 s x 25 per s)
t=3 h   7      881,402      1,151,403      270,001   other 23 partitions: lag ~10 each

The trace: In-place retry against a bounded retry with a dead-letter topic.

retry timelineruns offline
in place, forever:  attempt ✗ at 0 s, ✗ 1 s, ✗ 2 s ... partition 7 blocked, same error every second
bounded:            ✗ 0 s   retry ✗ +1 s   retry ✗ +2 s   retry ✗ +4 s
                    -> publish to orders.events.DLT, commit past 881,402 ✓, continue at 881,403 (cost: 7 s)
alert on total lag > 500,000 would fire after 500,000 / 25 per s = 20,000 s = 5.6 h

What you see: The error in the log.

consumer logruns offline
# illustrative output
ERROR inventory-consumer partition=7 offset=881402 trace=7c1e9a  ReservationParseException: missing field "sku"
(repeats every second for three hours)

Why: A retry with no bound is a decision to stop processing the partition.

The fix: A bounded retry into a dead-letter topic, immediate dead-lettering for deterministic errors, and an alert per partition.

What you see now: The same record after the fix.

consumer log and lagruns offline
# illustrative output
WARN  offset=881402 failed 4 times, published to orders.events.DLT, committed
partition 7 lag: 1 -> 0 within 8 s      orders.events.DLT depth: +1  (alert to owner)
Symptom, root cause, action
SymptomRoot causeAction
One partition's offset stuck, same error repeatingPoison record retried in placeSeek past after copying aside; bounded retry then DLT
Total lag looks smallOne partition of 24 is stuckAlert per partition: offset flat while lag > 0
Record would succeed laterEntity not there yet (ordering)Non-blocking retry topics, or fix the key and ordering

Land it Retrying forever is a decision to stop processing, and a bounded retry into a dead-letter topic with an alert is what turns a poison record into a ticket instead of an outage.

Likely follow-ups
"Show me the Spring Kafka error handler configuration for bounded retry and dead-lettering."

The bean is a DefaultErrorHandler constructed with a DeadLetterPublishingRecoverer and a back-off: new DefaultErrorHandler(new DeadLetterPublishingRecoverer(kafkaTemplate), new ExponentialBackOffWithMaxRetries(3)) with the back-off's initial interval at one second and multiplier two.

KafkaErrorConfig.javaruns offline
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
    var backOff = new ExponentialBackOffWithMaxRetries(3);   // retries after 1 s, 2 s, 4 s
    backOff.setInitialInterval(1_000);
    backOff.setMultiplier(2.0);
    var handler = new DefaultErrorHandler(new DeadLetterPublishingRecoverer(template), backOff);
    handler.addNotRetryableExceptions(DeserializationException.class, ValidationException.class); // dead-letter at once
    return handler;
}
// Result: one bad record costs seconds, then the partition moves

After three failed attempts the recoverer publishes the record to <topic>.DLT by default, with headers carrying the exception class, message, stack trace, and original topic, partition, and offset, and the handler then commits past the record so the partition moves.

The distinction between transient and deterministic errors is addNotRetryableExceptions(DeserializationException.class, ValidationException.class), which sends those straight to the dead-letter topic on the first failure — a malformed record will never succeed on retry. The handler is set on the container factory with factory.setCommonErrorHandler(handler).

The dead-letter topic needs to exist with at least as many partitions as the source, because the recoverer uses the same partition number by default.

"Why did it take three hours to notice? What is the alert?"

Because the alert, if there was one, was on total consumer lag, and total lag grew slowly — one partition out of twenty-four stuck, so lag climbed at one twenty-fourth of the production rate, and a threshold set for a whole-group outage took hours to cross.

And the error log line repeating every second is invisible without an alert on error rate per consumer. The right alert is per partition: for each partition, the committed offset has not advanced for more than a minute while its lag is greater than zero.

Burrow computes this directly as a per-partition status; with plain Prometheus it is kafka_consumergroup_lag > 0 and delta(kafka_consumergroup_current_offset[2m]) == 0, exported by the Kafka exporter with partition labels.

A second alert is the error-log rate for the consumer, from the log pipeline, which would have fired in the first minute. Both go to the owning team with the topic and partition in the message.

"What if the poison record was an ordering problem — the referenced entity really did not exist yet?"

Then dead-lettering after three retries in three seconds is too aggressive, because the record would have succeeded a minute later, and I need a different retry shape for that class of error.

Spring Kafka's non-blocking retries — @RetryableTopic — publish the failed record to a retry topic with a delay, so the main partition keeps flowing while this record waits and is reattempted from the retry topic after, say, one minute, then five, then thirty, before the dead-letter topic.

InventoryListener.javaruns offline
// ✅ FIX for "not yet" errors: the main partition keeps flowing, the record returns later
@RetryableTopic(attempts = "4", backoff = @Backoff(delay = 60_000, multiplier = 5))
@KafkaListener(topics = "orders.events", groupId = "inventory")
void on(OrderEvent e) { reserve(e); }
// Result: retries after 1 min, 5 min, 25 min, then the dead-letter topic

That handles "not yet" without blocking "everything after".

The deeper fix is in the data flow: if inventory needs the product to exist before it can reserve stock, the product event and the reservation command should share a key so they are ordered on one partition, or the consumer should create a placeholder from the reservation and fill it in when the product arrives.

Retrying is a patch over an ordering assumption that the topic design did not guarantee.

"How do you reprocess the dead-lettered records after the fix, safely?"

With a replay tool that publishes them back to the original topic, in their original order per key, using the headers the recoverer wrote.

The tool consumes the dead-letter topic, filters by the exception type and time range that the fix addresses, and for each record publishes to the original topic with the original key, so it lands on the same partition and after any newer records for that key — which means the consumer must handle an old record arriving after newer ones, usually by checking a version or timestamp in the payload.

The consumer's idempotency guard ensures a record that was in fact half-processed is not doubled. I run the replay in a small batch first, watch the consumer's error rate, then the rest.

The dead-letter topic records that were replayed get a marker — a second topic or a database row — so they are not replayed twice by the next engineer. And the incident's records stay in the dead-letter topic under its retention for audit.

Q125 · Scenario. "During a regional failover, the platform switched writes to the secondary region. Afterwards, 140 orders exist twice — once in each region — and 30 orders that customers were charged for exist in neither. Explain both groups."

Reveal answer

Strong answer Both groups come from the failover window, where the two regions were briefly both accepting writes and the replication between them was behind.

The 140 duplicates came from retries during the overlap:

  1. clients whose request to the primary timed out during the cut retried against the secondary;
  2. there was no idempotency key that both regions can check;
  3. the secondary's copy of the key table was behind by the replication lag;
  4. so the secondary created a second order for the same checkout.

Evidence: pairs of orders with the same cart and customer a few seconds apart in different regions.

The 30 charged-but-missing orders fell into the replication gap:

  1. the primary accepted and committed the order, and the charge went through to the payment provider;
  2. the order row had not replicated to the secondary when the primary was cut off;
  3. the primary's unreplicated writes were discarded when it was later rebuilt as a replica.

That is the data-loss window of asynchronous replication, the recovery point objective in practice.

Evidence: the payment provider's records versus both regions' order tables. Fix: reconcile against the payment provider as the source of truth for money — refund or recreate as appropriate — and merge duplicates by idempotency key.

Prevention:

  • idempotency keys stored with synchronous replication or in a globally consistent store;
  • a failover procedure that fences the old primary before promoting the secondary so both cannot accept writes;
  • measuring and publishing the replication lag as the accepted data-loss window;
  • a post-failover reconciliation job that runs automatically.

the Distributed Systems primer covers why "both regions accept writes" needs consensus or partitioned ownership, not hope.

Picture it The two regions' rows, the payment provider's records and the timeline of the failover window, with the arithmetic that gives about 30 lost orders (the idempotency key is the same idea as the idempotent consumer).

The setup: The platform takes 8 orders per second. Replication from region A to region B is 4 seconds behind. At 10:00:20 writes are switched to B while some clients still reach A until 10:01:05.

Make the invisible visible: The rows afterwards, for one duplicated checkout and one lost one.

orders per region and the providerruns offline
# illustrative output
region A orders                        region B orders                      payment provider
o-9100 key=k-91 10:00:25 committed     o-9500 key=k-91 10:00:31 (retry)     ch_81 order=o-9100
o-9002 key=k-80 10:00:19 committed     (never replicated)                   ch_77 order=o-9002
A was later rebuilt as a replica: o-9002 gone from A as well -> ch_77 charged, order exists nowhere

The trace: The timeline of the window.

failover timelineruns offline
10:00:15  A degraded, replication lag 4 s
10:00:20  writes switched to B, B promoted      A still takes writes from cached clients  ✗ both regions accept
10:01:05  A finally fenced                       overlap 45 s = 360 orders, 140 retried against B -> 140 duplicates
lost: 8 orders/s x 4 s lag = 32 unreplicated commits, about the 30 charged but missing

What you see: The reconciliation against the provider.

reconciliationruns offline
# illustrative output
duplicates (same key in both regions):         140
charges with no order in either region:         30
action: merge duplicates by key; recreate or refund the 30 from charge metadata

Why: Two regions accepted writes, and the replication gap was larger than the retries could hide.

The fix: Fence the old primary before promotion, keep idempotency keys and payment intents synchronously replicated, and reconcile after every failover.

Symptom, root cause, action
SymptomRoot causeAction
Same checkout twice, one per regionBoth regions accepted writes; key table behindFence first, synchronous key store, merge by key
Charged, no order anywhereAsync replication lag at promotionReconcile from the provider, charge metadata carries order details
Nobody knows the loss windowLag not measuredPublish replication lag as the accepted recovery point

Land it A failover with asynchronous replication always has a window where writes are lost or doubled; the design decides how big the window is and whether anyone can find what fell into it.

Likely follow-ups
"What does 'fencing the old primary' mean concretely for a PostgreSQL cluster and a Kubernetes platform?"

It means making it impossible for the old primary to accept a write after the decision to promote, before the promotion happens.

For PostgreSQL that is, in order: revoke the application role's connect privilege or change its password on the old primary, terminate its existing connections with pg_terminate_backend, and ideally set the instance to read-only or stop it, and only then run pg_promote() on the replica.

fence-then-promote.sqlruns offline
-- on the OLD primary, first
ALTER ROLE app_orders NOLOGIN;      -- or REVOKE CONNECT, or change the password
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'app_orders';
-- only then, on the replica
SELECT pg_promote();                -- promoting first is the split-brain window

Managed services such as Patroni do this with a distributed lock — the primary must hold a lease in etcd to keep accepting writes, and it demotes itself when the lease is lost.

At the platform level, the old region's gateway is set to return 503 or redirect, its DNS weight is set to zero, and its Kafka producers are stopped, so even a service that still has a database connection has no traffic.

The order matters: promote first and fence second is the split-brain window in which the 140 duplicates were created.

"How would idempotency keys have prevented the duplicates, given the replication lag?"

They would have prevented most of them, and the lag is why not all. The idempotency key is generated by the client at checkout start and sent with every attempt.

If the primary recorded the key and the order in one transaction and that transaction replicated before the cut, the secondary sees the key on the retry and returns the existing order — no duplicate.

idempotency_keys per regionruns offline
# illustrative output
idempotency_keys (region A)          idempotency_keys (region B, 4 s behind)
k-77  o-9001  ✓ replicated           k-77  o-9001  retry returns the existing order ✓
k-91  o-9100  committed 10:00:25     (no k-91 yet)  retry creates o-9500 ✗ duplicate, detectable later by key

If the transaction had not replicated, the secondary sees no key and creates a second order — a duplicate that the key cannot prevent by itself but can detect afterwards, because both orders carry the same key and the reconciliation finds them in seconds.

Without keys, the duplicates are only findable by heuristics — same customer, same cart, close in time — which is slower and less certain.

To prevent rather than detect, the key store has to be more available than the orders: synchronous replication for the small key table, or a globally consistent store for keys alone, which is cheap because keys are tiny and short-lived.

"The customers charged for orders that exist nowhere — what is the exact recovery, and how fast?"

The payment provider is the source of truth for money, so the recovery starts from its records.

A reconciliation query lists every charge in the failover window whose order id — sent to the provider as metadata at charge time — matches no order in either region. For each, the choice is recreate or refund.

If the order details can be recovered — from the charge metadata, from the cart in the session store, or from the customer's confirmation email — the order is recreated in the new primary with the original id and marked as recovered, and fulfilment proceeds.

If they cannot, the charge is refunded and the customer is told plainly what happened. Speed: the query runs within an hour of the failover, the refunds go out the same day, and the recreations within a day.

The lesson for the design is that the charge should carry enough metadata to rebuild the order, because the provider's record may be the only copy that survives.

"Would synchronous cross-region replication have avoided all of this, and what would it cost?"

It would have avoided the 30 lost orders, because a write is acknowledged only after the secondary has it, so the recovery point is zero.

It would not have avoided the duplicates on its own, because those came from both regions accepting writes, which is a fencing failure, not a replication one.

The cost is latency: every commit waits for a round trip to the other region, which between regions on the same continent is 20 to 80 milliseconds and across oceans is more, added to every write transaction; and availability, because if the secondary is unreachable the primary must either stop committing or fall back to asynchronous, and the fallback is where the loss window reopens.

For an order platform I would pay it for the small tables that matter most — idempotency keys and payment intents — and keep the bulk asynchronous with a monitored lag, which is what a 1-minute recovery point objective means in practice.

Q126. "What does a good post-mortem produce, and what makes one useless?"

Reveal answer

Strong answer A good post-mortem produces four things.

The four things:

  1. A timeline in minutes: when the fault began, when it was detected, when it was mitigated, when it was resolved. The gaps between those are the measurable things to shrink: detection time says the alerting was wrong, mitigation time says the runbook or the rollback was slow.
  2. A causal analysis that goes past the trigger to the conditions: not "the deploy had a bug" but "the deploy had a bug, the canary did not judge login success, and the rollback took twenty minutes because the schema change was not compatible".
  3. Actions with owners and dates: each one removes a condition rather than adding a checklist item, and is tracked to completion in the same system as feature work.
  4. A written account shared beyond the team: the same conditions exist elsewhere.

What makes one useless:

  • Blame: it makes the next incident's engineers hide the timeline.
  • A root cause stated as a person's mistake: that is where analysis stops instead of starting.
  • Actions that are "be more careful" or "add a review step": there is no mechanism.
  • No follow-up: the same post-mortem is written twice.

The practical test is whether, three months later, the actions are done and the class of failure cannot recur.

The practical test is whether, three months later, the actions are done and the class of failure cannot recur.

Picture it One incident turned into a timeline in minutes, the conditions behind it, and a tracker that shows after 90 days whether the post-mortem changed anything.

The setup: A deploy breaks login. The canary judged order error rate but not login success, and the rollback needed a schema change that was not backward compatible.

Make the invisible visible: The timeline in minutes.

timelineruns offline
# illustrative output
14:02  deploy starts, canary at 5 %          14:06  100 %, login failures 38 %
14:19  first alert (customer reports)         time to detect   = 17 min
14:24  rollback started                       14:44 rollback done (schema step slow)
                                              time to mitigate = 25 min from detection (14:19 to 14:44)

The trace: Trigger and conditions are different things. Each condition becomes one action.

Conditions and the actions that remove them
ConditionChecklist versionMechanism version
Canary did not judge loginReviewers check metrics cover the featurePipeline fails if the service declares no business metric
Rollback blocked by schemaBe careful with schema changesMigration linter blocks renames without an expand-contract marker
17 minutes to detectWatch the dashboard after deployAlert on login success rate

What you see: The tracker three months later.

post-mortem tracker at 90 daysruns offline
# illustrative output
incident  TTD    TTM    actions done at 90 d    recurrence
INC-211   17 min 25 min 4 of 4 (all mechanisms) no
INC-230    3 min 12 min 2 of 5 (40 %)           yes, same class
INC-248   55 min 20 min 1 of 3                  yes, same class

Why: Actions that depend on someone remembering decay, and unfinished actions leave the condition in place.

Symptom of the process, root cause, action
SymptomRoot causeAction
Same class of incident againChecklist actionsRewrite as mechanisms
Actions never finishedTracked outside the feature backlogSame backlog, above new work, monthly review
Fixed one service, twenty share the gapAnalysis stopped at the triggerAsk where else the condition exists, fix the template

Land it A post-mortem is a change to the system that produced the incident, and if the only thing it changes is people's feelings, it did not happen.

Likely follow-ups
"Give me an example of an action that removes a condition versus one that adds a checklist item."

Take the incident where a deploy broke login and the canary did not catch it. A checklist action is "reviewers must check that canary metrics cover the changed feature" — it depends on a person remembering under pressure, and it decays in a month.

service.yamlruns offline
# platform template for every service (illustrative)
canary:
  businessMetric: login_success_rate   # ✅ FIX: the pipeline fails if this key is missing
# ❌ TRAP: a review-time reminder to "check that canary metrics cover the feature" 

A condition-removing action is "the canary analysis template requires at least one business metric per service, and the pipeline fails if the service's metadata does not declare one" — it makes the omission impossible rather than discouraged.

Similarly, "be careful with schema changes" versus "the migration linter blocks renames without an expand-contract marker"; "check timeouts in review" versus "the HTTP client bean in the template cannot be constructed without a timeout".

The test I apply to every action is: if the same engineer made the same mistake next month, would this action stop it without anyone noticing? If the answer depends on someone being careful, it is a checklist item, and I keep looking for the mechanism.

"How do you run a blameless post-mortem when someone clearly made the mistake?"

By treating the mistake as data about the system that made it easy.

Someone ran a migration that renamed a column in one release; the question is not why they did that but why the system let a rename reach production in one step — no linter, no review rule, no test environment with a rolling deploy that would have shown the errors.

The person's action is recorded in the timeline factually — "at 14:02 the migration ran" — without adjectives, and the analysis asks what information they had and what the tooling allowed.

I say at the start of the meeting that the goal is to change the system and that nobody's name goes in the actions column as a cause.

The practical reason is not kindness: an engineer who fears blame edits the timeline, and a post-mortem with an edited timeline produces the wrong actions. Accountability sits in the action items — someone owns the linter — not in the cause.

"What are the metrics you track across post-mortems, and what do they tell you?"

Four. Time to detect — from fault start to first alert or report — which, when it is long, says the SLOs or the alerts are not measuring what customers feel.

Time to mitigate — from detection to the customer impact ending — which says whether rollback and runbooks work; a mitigation over thirty minutes usually means a rollback that was not possible.

Action completion rate at ninety days, which is the honesty metric: a team completing under half its actions is writing post-mortems as a ritual. And recurrence: incidents whose conditions match a previous post-mortem, which is the direct measure of whether the process works.

I do not track incident count as a target, because that drives under-reporting. The one number I show leadership is the recurrence rate, because it translates into "we are learning" or "we are not" without technical detail.

"The same class of incident happened three times in a year. What went wrong with the post-mortems?"

One of three things, and the actions from the first post-mortem tell me which. If the actions were checklist items, they did not remove the condition, and the second incident was inevitable — the fix is to rewrite them as mechanisms.

If the actions were mechanisms but were never completed, the tracking failed — the fix is to put post-mortem actions in the same backlog as features with a rule that they are prioritised above new work until done, and to review open ones monthly.

If the actions were completed and the incident recurred anyway, the analysis stopped at the trigger and missed a condition — for instance, it fixed the one service that failed and not the template that produced twenty services with the same gap.

That third case is the most instructive, and it is why a post-mortem's last question is always "where else does this condition exist?"

Q127 · Scenario. "Cloud spend doubled in the year after the move to microservices while traffic grew 20%. The CFO wants an explanation and a plan within a week. Where does the money go and what do you cut first?"

Reveal answer

Strong answer The evidence is the bill broken down by service and by category — compute, managed databases, network egress, observability — with utilisation beside each. The usual findings, ranked by size.

The usual findings, ranked by size:

  1. Idle compute: each of forty services runs a minimum of two or three pods sized for its peak, with CPU requests set high and utilisation at 10 to 15%, so the cluster is mostly reserved-but-idle. Fix: right-size requests from measured usage, run a vertical autoscaler in recommendation mode, and consolidate tiny services onto shared node pools.
  2. Managed databases: forty small database instances each with a base fee, backups, and a replica, for datasets that fit in memory. Fix: consolidate onto fewer instances with logical databases where ownership rules allow.
  3. Observability: tracing at 100% sampling and INFO logs from forty services, often a fifth of the bill. Fix: tail sampling, log sampling, and shorter hot retention.
  4. Network: chatty synchronous calls across availability zones paying cross-zone egress, and a mesh doubling the hops. Fix: zone-aware routing and batching the chattiest calls.
  5. Sidecars: a proxy per pod adds 10 to 20% of compute. Ambient mode or a lighter mesh helps.

The plan for the CFO: the three largest items with expected savings and dates, a monthly cost per service on every team's dashboard so cost becomes a metric like latency, and the honest note that some of the increase — a platform team, redundancy per service — is the price of the independence that was the point.

Picture it The monthly bill as numbers at three moments, the idle-compute arithmetic behind the biggest line, and what each cut is worth.

The setup: Forty services, each with 2 to 3 pods, its own small database, tracing at 100% and a sidecar per pod. Traffic grew 20% while spend doubled.

Make the invisible visible: The bill by category (in thousands of dollars per month) before the move, today, and after the plan.

monthly bill at three momentsruns offline
# illustrative output   $k per month
                before move   today   after month 1   after month 4
compute              55        90         60              55
managed databases    15        35         35              20
observability         8        40         20              18
network               7        20         20              14
platform/other       15        15         15              13
total               100       200        150             120      (-25 % in month 1, -40 % by month 4)

The trace: Why compute is the largest line: reserved capacity far above use.

idle compute arithmeticruns offline
40 services x 3 pods = 120 pods;  120 x 2 vCPU requested = 240 vCPU reserved
measured use at 12 % of requests = ~29 vCPU
right-sized to ~50 % utilisation: 29 / 0.5 = ~58 vCPU requested  ->  ~75 % of the reservation released
the cluster autoscaler then removes the empty nodes

What you see: The cost-per-service view that makes this a metric the owning team sees.

cost per serviceruns offline
# illustrative output
service     compute  database  observability  network  sidecar share
order        high      own        medium        medium   in compute
payment      medium    own        low           low      in compute
... 30 small services: 2-3 pods idle at 10-15 %, own database each

Why: Each service carries a floor of idle capacity, database and telemetry, multiplied by forty.

The fix: Right-size requests, tail-sample, consolidate small databases by tier, route within zones, and show cost per service to the owner.

Symptom, root cause, action
SymptomRoot causeAction
Cluster mostly reserved, little usedRequests set for peak, 10 to 15% utilisationVPA recommendations, right-size, remove empty nodes
Forty database billsOne instance per small serviceConsolidate by tier, keep critical services separate
Observability a fifth of the bill100% tracing, INFO logsTail sampling, log sampling, shorter hot retention
Cross-zone egress and mesh hopsChatty synchronous callsZone-aware routing, batch the chattiest calls

Land it The bill doubled because forty services each carry a floor of idle capacity, database, and telemetry — right-size the floor, show cost per service to the team that owns it, and name the part that is the price of the architecture.

Likely follow-ups
"How do you right-size CPU requests without causing throttling or eviction?"

From measured usage, with headroom, and separately for requests and limits. The Vertical Pod Autoscaler in recommendation mode — updateMode: "Off" — watches each container's usage for a week and publishes a recommended request at a high percentile of observed use.

vpa-inventory.yamlruns offline
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: inventory
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: inventory
  updatePolicy:
    updateMode: "Off"        # recommendation mode: publishes numbers, changes nothing

I set the CPU request to that recommendation, which is what the scheduler reserves, and I set no CPU limit or a generous one, because a CPU limit causes throttling as the mesh question showed, while a missing limit only means the container can use idle cycles.

Memory is the opposite: the request and the limit are set equal at the recommendation plus 20%, because exceeding a memory limit is an out-of-memory kill and memory cannot be borrowed.

The verification is the node's allocation versus its usage: after right-sizing, requested CPU across the cluster should be within 50% of actual usage, down from the 10-to-15% utilisation the CFO is paying for. Then the cluster autoscaler removes the empty nodes.

"Cost per service on a dashboard — how do you attribute shared costs like the mesh, Kafka, and the cluster nodes?"

Directly where possible and proportionally where not.

Compute is attributed by the pod's requests: a tool such as OpenCost or Kubecost multiplies each pod's requested CPU and memory by the node's hourly price and sums by namespace or by a team label, which puts the idle-request problem on the team that set the requests.

The sidecar's cost goes to the pod it sits beside, which is exactly right. Managed databases are attributed to their owning service by tag.

Shared infrastructure — Kafka, the observability stack, the gateway — is split by usage: Kafka by bytes produced and consumed per topic, logs and traces by volume per service, the gateway by request count.

What is left — the platform team, cluster control planes — is shown as a platform line, not hidden in the teams' numbers, because pretending it is attributable makes the numbers lies.

The dashboard shows each team its direct cost, its share of shared cost, and the trend.

"Consolidating forty small databases into fewer instances — doesn't that violate the ownership rule?"

Not if the isolation is by permission rather than by instance.

The ownership rule is that only the owning service reads and writes its data, and a database server with forty logical databases, each with its own role that can access only its own database, keeps that rule exactly.

What is lost is failure isolation — one instance's outage takes forty services' data with it — and performance isolation, since one service's heavy query competes with others for the same CPU and I/O. So I consolidate by tier: the critical path services — order, payment, inventory — keep their own instances with their own replicas, and the thirty small ones with modest load and non-critical data share two or three instances.

The saving is the base fee times thirty. The rule I add is that a service cannot be moved to the shared instance if its load is more than a small fraction of the instance's capacity, so the shared instance never becomes a noisy-neighbour problem.

"The CFO asks why you cannot just cut 50% next month. What do you say?"

I show the plan with dates and say which cuts are safe fast and which are not. Right-sizing requests and tail-sampling traces are configuration changes with immediate effect and low risk; they are perhaps 25% of the bill and can be done in the first month.

Consolidating databases and merging chatty services are migrations, each a few weeks with a rollback plan, and doing them all at once is how the cost-cutting causes an outage that costs more than it saves.

So the honest answer is 25% in month one, 40% by month four, and the remaining part of the increase — the platform team, per-service redundancy, the second region — is the cost of the architecture's independence and resilience, which I would defend with the outage history from before the migration.

What I would not do is cut the observability budget below what is needed to see incidents, or drop redundancy on the checkout path, and I would say that in the meeting rather than let it be discovered.

Q128 · Scenario. "Since the mesh was rolled out, about one pod start in ten fails: the application logs 'connection refused' to the database in its first two seconds and crashes, then starts fine on the restart. Why?"

Reveal answer

Strong answer The application is starting before its sidecar proxy is ready to carry traffic.

With a sidecar mesh, all of the pod's outbound traffic is redirected through the proxy container; if the application container starts its database connection pool while the proxy is still initialising, the redirected connection has nowhere to go and is refused.

The one-in-ten rate is the race: usually the proxy wins, sometimes the application does. Evidence: container start timestamps in the pod's events, the proxy's ready time versus the application's first connection attempt, and whether the failure correlates with node load (slower proxy start).

Causes ranked:

  1. no ordering between the sidecar and the application: the mesh injects the proxy as an ordinary container;
  2. the application's pool set to fail fast on the first connection error rather than retry;
  3. no startup probe, so the crash counts as a failure rather than a slow start.

Fix:

  1. on Kubernetes 1.29 and later, native sidecar containers (an init container with a restart policy of Always) start the proxy before the application and keep it running, and Istio and Linkerd both support that mode;
  2. short of that, the mesh's "hold application until proxy starts" setting does the same.

Also make the pool retry its initial connection with backoff (HikariCP's initializationFailTimeout can be set to wait), and add a startup probe. Prevention: a pod start test in the platform's mesh upgrade checklist.

Picture it Three pod starts of the payment service on the order platform, showing the race between the proxy and the database pool, and the failure rate arithmetic (see the sidecar and mesh block).

The setup: Each pod runs the payment application and an istio-proxy container. The application opens its database pool 1.5 seconds after it starts, and all its outbound traffic goes through the proxy.

Make the invisible visible: Three starts, seconds after the pod starts.

pod start lanesruns offline
# illustrative output
pod A (idle node):  proxy ready 0.8 s    app opens DB pool 1.5 s   ✓ connected
pod B (busy node):  proxy ready 2.6 s    app opens DB pool 1.5 s   ✗ connection refused, context fails, container exits
pod B restart:      proxy already up     app opens DB pool 1.4 s   ✓ connected

The trace: What the numbers say about how often this bites.

failure arithmeticruns offline
1 start in 10 loses the race
200 pod starts a day (40 services x 5 pods, rolling updates)  ->  ~20 failed first starts a day
a checklist that starts 1 pod sees the failure 10 % of the time
100 starts: P(no failure) = 0.9^100 = ~0.003 %   -> a hundred-start test cannot miss it

What you see: Pod status and the application log.

consoleruns offline
# illustrative output
$ kubectl get pods -l app=payment
NAME              READY  STATUS   RESTARTS      AGE
payment-6d8f-abc  2/2    Running  1 (45s ago)   52s
HikariPool-1 - Exception during pool initialization ... Connection refused

Why: The proxy is an ordinary container, so nothing makes the application wait for it, and the pool tries once.

The fix: Native sidecar ordering, and a pool that waits.

What you see now: The same hundred starts.

consoleruns offline
# illustrative output
100 pod starts: restarts 0, all Ready on the first attempt
HikariPool-1 - Start completed.
Symptom, root cause, action
SymptomRoot causeAction
Connection refused in the first 2 seconds, then fineApp started before the proxyNative sidecar (restartPolicy: Always), or hold-until-proxy-ready
Pool crashes the app on the first errorinitializationFailTimeout is 1 ms by defaultSet it to 30 seconds, add a startup probe
Job pods never completeSidecar outlives the appNative sidecars stop when the app exits

Land it A sidecar is a dependency of every outbound byte, so it must be running before the application opens its first connection — and native sidecar ordering is how the platform guarantees that.

Likely follow-ups
"What does the native sidecar configuration look like in the pod spec, and what does it change about termination?"

A native sidecar is an init container with restartPolicy: Always — that one field is the whole feature, generally available since Kubernetes 1.33 as of Aug 2026.

pod spec (what the injector emits)runs offline
spec:
  initContainers:
    - name: istio-proxy
      image: istio/proxyv2
      restartPolicy: Always            # ✅ FIX: native sidecar, starts first, stays running
      startupProbe:
        httpGet: { path: /healthz/ready, port: 15021 }
  containers:
    - name: payment                    # starts only after the proxy's startup probe passes

Kubernetes starts init containers in order and waits for each to be ready before the next; a native sidecar starts, its startup probe passes, and only then do the application containers start, so the proxy is guaranteed to be ready first.

Unlike a normal init container, it keeps running for the pod's lifetime.

Termination is the mirror image: the application containers are stopped first, and the native sidecars are stopped only after they exit, so the proxy stays up while the application finishes its in-flight requests and drains — which fixes the other classic sidecar problem, where the proxy died before the app and the app's final calls failed.

In Istio it is enabled with values.pilot.env.ENABLE_NATIVE_SIDECARS=true, and the injector then emits the proxy as an init container.

"Why would HikariCP's initializationFailTimeout matter here, and what value?"

It controls what the pool does when it cannot get its first connection at startup. The default is 1 millisecond, which means "try once, and if it fails, throw" — so the application context fails and the pod crashes, which is what happened.

application.ymlruns offline
spring:
  datasource:
    hikari:
      initialization-fail-timeout: 30000   # ✅ FIX: retry for up to 30 s (default 1 ms: try once, then throw)

Setting it to a positive value, say 30,000 milliseconds, makes the pool retry for up to thirty seconds before giving up, which rides through the proxy's startup race.

Setting it to a negative value makes the pool start without any connection at all and try lazily on first use, which is the most tolerant but hides a genuinely misconfigured database until the first request.

I use 30 seconds combined with a startup probe of similar length, so a pod that cannot reach its database within thirty seconds is restarted with a clear log message rather than either crashing instantly or sitting broken. The setting is spring.datasource.hikari.initialization-fail-timeout.

"What about the reverse race — the application finishing before the sidecar during a Job?"

That is the other half of the same problem and it plagued Kubernetes Jobs for years. A batch pod runs its work and exits, but the sidecar keeps running, so the pod never completes and the Job hangs.

Before native sidecars the workarounds were ugly: the application calling the proxy's /quitquitquit endpoint before exiting, or a shared volume with a completion file that a wrapper script watched.

Native sidecars fix it for the same reason as the startup race: when all the regular containers have exited, Kubernetes stops the native sidecars and the pod completes.

For a platform with reconciliation jobs run as Kubernetes CronJobs that need the mesh for their outbound calls, this is the deciding reason to adopt the native mode.

The check that it is working is that Job pods reach Completed without any of the old workaround code.

"How would you have caught this in the mesh upgrade checklist?"

With a pod-start test that runs a hundred starts and counts failures. A one-in-ten failure is invisible if the checklist starts one pod and watches it, and obvious if it starts a hundred.

The test is a Kubernetes Job or a script that scales a canary deployment of a representative service from zero to twenty, five times in a row, in the staging cluster with the new mesh version, and asserts that every pod reaches Ready on its first attempt with zero restarts — the restart count in the pod status is the metric.

That test belongs in the mesh upgrade pipeline, along with the latency comparison from the earlier question and a check that Jobs complete.

More generally, any platform change that touches every pod — mesh, base image, node image, JDK — gets the same three tests: pod starts cleanly at scale, request latency unchanged, Jobs complete.

The restart-count metric across the fleet is also a standing alert, because a fleet-wide rise in first-start restarts is exactly this incident.

Q129 · Scenario. "The autoscaler scaled the inventory consumer from 12 to 40 pods during a backlog, but lag did not fall any faster, and the pods sat at 5% CPU. The topic has 12 partitions. Explain and fix the scaling."

Reveal answer

Strong answer A consumer group cannot have more active members than the topic has partitions: with 12 partitions, the 13th to 40th pods received no assignment and sat idle, so scaling past 12 bought nothing.

And CPU was the wrong signal in the first place — the consumer is I/O-bound on its database and on the broker, so it never showed high CPU even when saturated, which means a CPU-based autoscaler would never have scaled correctly in either direction.

Evidence: the group's partition assignment showing 28 members with no partitions; the consumer's per-record processing time and database wait; and the autoscaler's metric.

Causes ranked:

  1. partition count as the hard ceiling;
  2. CPU as the scaling metric for an I/O-bound workload;
  3. single-threaded processing per partition, so each of the 12 active pods is limited by its own latency to the database.

Fix:

  1. scale on consumer lag instead of CPU: KEDA's Kafka scaler exposes lag as an autoscaling metric and caps replicas at the partition count;
  2. raise the partition count with the ordering caveats from earlier (drain first);
  3. increase per-pod throughput by batching database writes per poll, since 12 pods doing 10 times the work per poll beats 40 pods doing nothing.

Prevention: partition counts chosen with growth headroom, and autoscaling metrics chosen per workload type — lag for consumers, requests-in-flight or latency for services, CPU only for compute-bound work.

Picture it The inventory consumer group with 12 partitions and 40 pods, lag at three moments, the drain-time arithmetic before and after batching, and which signal fits which workload.

The setup: The orders topic has 12 partitions and takes 11,500 messages per second. Each consumer pod handles 1,000 records per second (1 ms of database round trip per record). A backlog of 1,200,000 builds up and the autoscaler goes from 12 to 40 pods.

Make the invisible visible: The group's assignment.

consumer group assignmentruns offline
# illustrative output
inventory-consumer-0  .. -11   partitions 0..11 (one each)   CPU 5 %, waiting on the database
inventory-consumer-12 .. -39   no partitions assigned          idle (28 pods)

The trace: Lag at three moments.

lag over timeruns offline
# illustrative output
t=0       12 pods   lag 1,200,000   drain = 12 x 1,000 - 11,500 = +500 per s
t=10 min  40 pods   lag   900,000   still 12 workers: 500 x 600 s = 300,000 drained
t=20 min  40 pods   lag   600,000   drain time at this rate: 1,200,000 / 500 = 2,400 s = 40 min

What you see: The same drain after batching the database writes: 12 pods at 10,000 records per second each.

drain arithmetic after the fixruns offline
12 x 10,000 - 11,500 = 108,500 per s net drain
1,200,000 / 108,500 = ~11 s        (partition count and pod count unchanged)
KEDA: lag 40,000 / lagThreshold 5,000 = 8 pods;  lag 1,200,000 asks for 240, capped at maxReplicaCount 12

Why: Partitions are the parallelism, and CPU does not move for a workload that waits on I/O.

The fix: Scale on lag with a cap at the partition count, and cut per-record round trips.

Workload, right signal, why
WorkloadSignalWhy
Kafka consumerConsumer lag, capped at partitionsExtra pods beyond the partition count get nothing
I/O-bound request serviceIn-flight requests or latencyThey rise before CPU does
Compute-bound serviceCPU utilisationCPU is the honest signal
Scheduled batchNone, fixed Job parallelismWork is known in advance

Land it Partitions are the parallelism, lag is the signal, and CPU tells you nothing about a consumer that spends its life waiting on a database.

Likely follow-ups
"Show me the KEDA configuration for scaling on lag, and explain the thresholds."

A ScaledObject targeting the consumer Deployment with a kafka trigger: bootstrapServers, consumerGroup: inventory, topic: orders, lagThreshold: "5000", and activationLagThreshold: "100", with minReplicaCount: 3 and maxReplicaCount: 12.

keda-inventory.yamlruns offline
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: inventory-consumer
spec:
  scaleTargetRef:
    name: inventory-consumer
  minReplicaCount: 3
  maxReplicaCount: 12              # = partition count
  triggers:
    - type: kafka
      metadata:
        bootstrapServers: kafka:9092
        consumerGroup: inventory
        topic: orders
        lagThreshold: "5000"
        activationLagThreshold: "100"
        excludePersistentLag: "true"   # a stuck partition does not drive scaling

KEDA reads the group's lag from the broker, divides by the lag threshold, and asks the Horizontal Pod Autoscaler for that many replicas, capped at the maximum — so a lag of 40,000 asks for 8 pods.

The threshold is the lag one pod is expected to clear comfortably in the scaling window; at 500 messages a second per pod and a target of ten seconds of backlog per pod, 5,000 is the number.

The activation threshold keeps the deployment at its minimum during normal trickle traffic so it does not flap.

The cap at the partition count is the correction for the incident, and I would set excludePersistentLag: true so a stuck partition, as in the poison-message question, does not drive scaling for lag that no number of pods can clear.

"How do you raise the partition count on a live topic without breaking ordering?"

Adding partitions changes the hash-to-partition mapping, so a key that went to partition 3 may go to partition 15 afterwards, and for a while the old partition still holds unprocessed records for that key while new ones arrive on the new partition — two consumers can then process the same key concurrently and out of order.

key mappingruns offline
# illustrative output
key SKU-77   12 partitions: partition 3        after alter to 36 partitions: partition 15
partition 3 still holds unprocessed SKU-77 records while new ones land on partition 15
-> two consumers, one key, out of order

The safe procedure is to drain first:

  1. stop producers or pause them at the outbox relay;
  2. wait until consumer lag is zero on every partition so nothing for any key is in flight;
  3. add the partitions with kafka-topics --alter --partitions 36;
  4. let the consumer group rebalance;
  5. resume producers.

The pause is a minute or two. If a pause is not acceptable, the alternative is a new topic with the desired count, producers switched to it by flag once consumers of the old topic have drained, which is the same idea with more moving parts.

Either way the partition count should have been chosen with headroom — three times the current consumer count — so this is rare.

"Why would batching database writes per poll help more than adding pods?"

Because the per-record cost is dominated by round trips, not by work.

A consumer that processes 500 records per poll with one INSERT or UPDATE each pays 500 round trips of a millisecond or so, which is half a second per poll and caps the pod at about a thousand records a second.

Grouping the same 500 into one batched statement — JDBC batch with rewriteBatchedStatements or a single multi-row upsert — is one or two round trips and a few milliseconds, so the same pod does ten thousand a second.

StockWriter.javaruns offline
// ❌ TRAP: one round trip per record
for (var r : records) jdbc.update("UPDATE stock SET reserved = reserved + ? WHERE sku = ?", r.qty(), r.sku());
// ✅ FIX: one batch per poll, then commit offsets after the batch commits
jdbc.batchUpdate("UPDATE stock SET reserved = reserved + ? WHERE sku = ?", batchArgs);
// Result: 500 round trips become one or two

Twelve pods at ten times the throughput is far more than forty pods at the old rate, and it does not touch the partition count at all.

The constraint is atomicity: the batch and the offset commit should be in one unit, so a crash between them does not lose or double records — the idempotency guard makes doubling harmless, and committing offsets after the batch commit makes loss impossible.

The evidence for this fix is the per-record processing time in the consumer's metrics, which is almost all database wait.

"What are the right autoscaling signals for the other kinds of workload on the platform?"

The signal should be the thing that actually limits the workload.

For a request-serving service that is I/O-bound, the right signals are in-flight requests per pod or request latency, because they rise before CPU does; the HPA supports custom metrics through the metrics adapter, and a target of, say, 50 in-flight requests per pod with a p95 latency guard works well.

For a compute-bound service — image processing, a pricing engine — CPU is honest and the plain HPA on CPU utilisation is right. For a consumer, lag, as we said. For a scheduled batch, no autoscaling; a Job with a fixed parallelism.

For anything, the scaling window matters: a spike shorter than the time to start a pod cannot be handled by scaling at all, which is why the flash-sale design pre-scales.

I write the chosen signal into the service's metadata so the platform can warn when a consumer is configured to scale on CPU.

Q130 · Scenario. "The shared Redis cluster went down for four minutes. Every user-facing service returned errors for the full four minutes, even though Redis was 'only a cache'. What was wrong with the design?"

Reveal answer

Strong answer A cache that takes the site down when it fails was a dependency, not a cache.

Evidence: the services' behaviour on a cache miss versus a cache error (most treat them differently — a miss falls through to the source, an error throws), what else lived in Redis (sessions, rate-limit counters, idempotency keys, locks), and the load the source databases would have taken if the caches had all fallen through at once.

Causes ranked: cache client errors propagated as request failures instead of being treated as misses; state that was not cacheable at all — sessions, locks, idempotency keys — living in the same cluster with no durable backing, so when Redis died the state was gone, not merely uncached; and, had the services fallen through correctly, no load shedding on the databases, which would then have taken the full traffic cold and probably fallen over too.

Fix: wrap the cache client in a breaker with "treat as miss" semantics and a short timeout; move session and idempotency state to a durable store with Redis as an accelerator in front, or to a Redis deployment with persistence and replicas treated as a database; and put bulkheads and shedding on the fall-through path so a cache outage degrades to slow rather than to down.

Prevention: a chaos experiment that stops Redis in staging and expects the site to stay up, slower.

Land it If losing the cache loses the site, either the cache errors were not handled as misses or something that was not cache was living there — usually both.

Likely follow-ups
"What does 'treat a cache error as a miss' look like in code with Spring's cache abstraction?"

Spring's CacheErrorHandler is the hook.

By default an exception from the cache store propagates and fails the request; a custom handler overrides handleCacheGetError to log at WARN, increment a metric, and return — so the @Cacheable method proceeds as if the key were absent and calls the real source — and overrides handleCachePutError likewise so a failed write is ignored.

It is registered by implementing CachingConfigurer and returning it from errorHandler().

That alone stops errors from propagating, but not slowness: a Redis call that hangs for five seconds still parks the thread, so the Lettuce client needs a command timeout — spring.data.redis.timeout=50ms — and a circuit breaker around the cache operations so that after a burst of failures the service stops calling Redis at all for thirty seconds and goes straight to the source.

With those three, Redis dying costs latency and database load, not errors.

"If all the caches fall through correctly, the databases take the full load cold. How do you stop that being the next outage?"

By making the fall-through bounded rather than unlimited.

Each service's database access already has a bulkhead sized to its pool, so the number of concurrent cold queries per pod is capped and the excess is shed with a 503 — that keeps the database alive at the cost of some requests failing, which is the degraded-not-down goal.

Single-flight loading per key means a hundred requests for the same product become one query, which is most of the reduction.

And the most valuable trick is keeping a stale copy: the local Caffeine cache holds entries past their expiry as a last resort, served only when the shared cache is unavailable and the database is shedding, so a product page renders with a five-minute-old price rather than an error.

The load test that proves it is a cold-start test with Redis stopped, ramping traffic to normal peak and watching database CPU and the shed rate. If the database saturates, the bulkhead is too large.

"Sessions and idempotency keys in Redis — where should they live instead, and is Redis ever acceptable?"

They are state, so they need a store with durability guarantees: idempotency keys belong in the owning service's database next to the data they protect, because the whole point is that the key and the order commit together; sessions belong in a durable key-value store or, for a stateless design, in a signed token the client holds.

Redis is acceptable for either only if it is operated as a database rather than a cache: append-only persistence with appendfsync everysec, replicas with automatic failover, and an understanding that a failover can lose the last second of writes — which for sessions is fine and for idempotency keys is not.

The clean pattern is that Redis in front of a durable store is an accelerator: the session is read from Redis, and on a miss from the database, and written to both.

The rule I write down is that anything whose loss changes what a customer is charged does not live in a cache, even a persistent one.

"The fix didn't work — errors are handled as misses and the site still went down when Redis failed. What is left?"

Then something else depended on Redis in a way the cache abstraction did not cover.

The suspects are the rate limiter at the gateway, which fails closed if its Redis call errors and rejects everyone; distributed locks — a ShedLock or Redisson lock on a critical path that cannot be acquired; a pub/sub channel for cache invalidation whose subscriber blocks on reconnect; or a session filter that runs before the cache handler and throws.

Each of these needs its own fail-open behaviour: the rate limiter falls back to a local bucket, the lock falls back to a database lease, the subscriber reconnects asynchronously.

The way to find them is a dependency scan — every bean that holds a Redis connection — and the way to prove it is the chaos experiment that stops Redis in staging, which is the test that should have run before the fix was declared done.

The list of Redis clients in a platform is always longer than anyone remembers.

Q131. "'You build it, you run it' — what does that actually require from the organisation for it to work, rather than just meaning developers get paged?"

Reveal answer

Strong answer The phrase means the team that writes a service also owns its production behaviour: its deploys, its alerts, its on-call, its incidents. For that to be more than a pager handed to developers, five things have to exist.

A platform that makes the operational work small: a service template with logging, tracing, health checks, and resilience defaults built in; a deploy pipeline with canaries and rollback; and dashboards generated from the template, so a team of six can run its services in a few hours a week.

Ownership that is real: the team can change its deploy schedule, its infrastructure sizing, and its dependencies without a ticket to another department.

An on-call that is humane: a rotation of at least five or six people, alerts tuned to burn rate so pages mean customers, a rule that a noisy week is followed by alert-fixing time, and compensation for the rota.

Budget for reliability: the error-budget policy gives the team a legitimate reason to say no to a feature when the budget is spent, and management honours it. And post-mortems without blame, so incidents produce fixes rather than fear.

Without the platform, the phrase means every team builds its own tooling badly; without real ownership, it means responsibility without authority; and without humane on-call, it means the best engineers leave.

Land it "You build it, you run it" is a promise the organisation makes to the team — platform, authority, and a survivable rota — before it is a duty the team takes on.

Likely follow-ups
"A team of four owns six services and is on call every third week. What do you do?"

That rota is not survivable, and I would say so with numbers: at four people, each person is primary one week in four and secondary another, which is half their year on call, and at six services the alert volume is six times what a service should produce.

Two fixes, in order.

First, consolidate the rota: merge this team's rota with a neighbouring team's for the same domain, so eight people cover twelve services and each person is primary one week in eight — the services do not have to merge for the rota to.

Second, cut the alert volume: switch every alert to burn-rate on customer-facing SLOs, which typically removes three quarters of pages, and give the team a week of alert-fixing time before the new rota starts.

If the services are genuinely too many for the team, merging services is the longer answer, and I would look at whether the six always deploy together. What I would not accept is "that is just how it is", because the good engineers will leave first.

"What does the platform team owe the product teams, concretely, and how is that measured?"

The platform team owes a paved road that makes operating a service cheap, and it is measured like a product.

The deliverables are the service template, the deploy pipeline with canaries, the observability stack with generated dashboards and alerts, the resilience defaults, and a support channel with a response time.

The metrics are the ones the product teams feel: time from repository creation to first production deploy for a new service, which should be under a day; deploy lead time and frequency per team; pages per team per week; and the fraction of services on the current template version.

I also survey the teams quarterly with one question — what is the most annoying thing about running your service — and the answers become the platform backlog.

The failure mode of platform teams is building what is interesting rather than what removes toil, and measuring adoption and toil keeps that honest.

"How do you make the error-budget policy stick when a product manager wants the feature shipped anyway?"

By agreeing the policy before the argument, with the people who will have it.

The policy is written down and signed by engineering and product leadership: when a service's error budget for the window is spent, the team's next work is reliability until the burn rate is under one, and feature deploys on that path need a review.

Then when the conflict arrives, it is not the engineer against the product manager; it is both of them against a document their bosses signed, and escalation is to the people who agreed it.

The policy also gives product something: when the budget is healthy, engineering does not get to block features on vague reliability concerns, because the budget says there is room for risk.

In practice the policy is honoured about the second time it is invoked, after the first time it was overridden and the overriding caused the outage the budget was warning about.

I would rather have a policy that is occasionally overridden with a named decision-maker than no policy.

"Is there a version of this that does not work for a company of your size, and what do you do then?"

Yes: below about fifteen engineers, there is no capacity for a platform team, and forty services owned by three teams means each team runs a dozen, which is where the ninety-day question in this drill starts.

At that size the honest answer is fewer services — a modular monolith or three or four services — so that "you build it, you run it" means one team runs one thing and the platform is a well-configured pipeline rather than a team.

Between fifteen and fifty engineers, one or two platform engineers embedded in the largest team can maintain the template and the pipeline. Above fifty, the platform team is a team.

The principle does not scale down by lowering the standards; it scales down by lowering the number of things to run. A small company that adopts the phrase and forty services gets the pager without the platform, and that is the failure mode the question describes.

Q132 · Scenario. "A team rewrote the product service from servlet-based Spring MVC to reactive WebFlux for scalability. Throughput went up, but now a slow pricing dependency makes the entire service unresponsive within seconds instead of degrading. What changed?"

Reveal answer

Strong answer The rewrite removed the accidental bulkhead that the servlet thread pool provided and replaced it with nothing. In the servlet model, a slow dependency could park at most the pool's 200 threads, and the failure was gradual.

In the reactive model, there are a handful of event-loop threads and an unbounded number of in-flight requests, each holding memory and a pending call to pricing; when pricing slows, tens of thousands of requests pile up in seconds, the event loop is fine but memory and the downstream connection pool are exhausted, and — the most common specific cause — someone blocked an event-loop thread with a synchronous call (a JDBC query, a blocking HTTP client, a .block()), which stalls every request on that loop at once.

Evidence: the reactor's blocking-call detector (BlockHound in tests), the in-flight request count, memory growth, and a thread dump showing an event-loop thread in a blocking call.

Causes ranked: a blocking call on the event loop; no concurrency limit on the pricing client; and no timeout on the reactive pipeline (timeout() is explicit in Reactor, not a default).

Fix: move any blocking work to a bounded elastic scheduler or, better, to a non-blocking client; add timeout, Resilience4j's reactive operators for bulkhead and breaker, and a request-level concurrency limit; and load-test with the dependency slowed.

Prevention: reactive is a different failure model, and the resilience controls have to be reintroduced explicitly, because the thread pool that used to provide them is gone.

Land it Reactive makes waiting free, which means the limits that threads used to impose must now be written down as timeouts, bulkheads, and breakers — and one blocking call on the loop undoes all of it.

Likely follow-ups
"How do you find a blocking call on the event loop in production, not just in tests?"

With a thread dump and one metric.

The event-loop threads are named reactor-http-nio-N; a thread dump — jcmd <pid> Thread.print or the actuator's threaddump endpoint — taken during the stall shows each one, and any that is in SocketInputStream.read, a JDBC driver, Object.wait, or a CountDownLatch is blocked; a healthy event-loop thread is in epoll or a Reactor operator.

Reactor Netty also exposes an event-loop busy time metric, and a loop that reports near 100% busy while throughput is low is stuck.

For a permanent detector, BlockHound can run in production with its allowBlockingCallsInside configuration for known-safe spots, throwing on any blocking call from a non-blocking thread; the cost is a small overhead and the risk of a false positive taking down a request, so I run it in staging under load and in production behind a flag during an investigation.

The offending stack frame names the library, which is usually the fix.

"Show me the reactive resilience chain around the pricing call."

The pricing client returns a Mono<Price>, and the chain reads: pricingClient.get(id).timeout(Duration.ofMillis(300)).transformDeferred(BulkheadOperator.of(bulkhead)).transformDeferred(CircuitBreakerOperator.of(breaker)).onErrorResume(e -> Mono.just(Price.unavailable())).

The order matters: the timeout is innermost so the bulkhead and breaker see a timeout as a failure; the bulkhead limits concurrent in-flight calls to pricing — Resilience4j's reactive bulkhead is a semaphore of, say, 100 permits with a zero wait, so the 101st call fails immediately instead of queueing; the breaker counts failures and opens; and the fallback produces a page without a price rather than an error.

On top, a request-level limit: a RateLimiter or a global bulkhead in a WebFilter caps total in-flight requests per instance, which is the limit the servlet pool used to impose.

Each operator exposes metrics, and the bulkhead's rejected count is the early warning that pricing is slow.

"Was the rewrite worth it? What would you have done instead?"

Probably not, for a product service whose work is a database read and a few HTTP calls, and as of Aug 2026 I would have used virtual threads on Spring MVC instead.

spring.threads.virtual.enabled=true gives the same freedom from thread-per-request limits with the code unchanged — blocking calls are fine, stack traces are readable, JDBC works — and the throughput gain for I/O-bound services is comparable to reactive.

It has the same trap this incident shows, that the accidental bulkhead disappears, but the fix is a semaphore around each dependency rather than a rewrite of every handler into a chain.

WebFlux still earns its place for streaming — server-sent events, large responses, backpressure from a client — and for a gateway that proxies bytes.

For a CRUD-plus-calls service, the cost of the rewrite, the retraining, and the new failure model outweighs a throughput gain that virtual threads deliver for one property. I would say that plainly in the review.

"Memory exhaustion in the reactive version — where does the memory actually go?"

Into the in-flight requests. Each pending request holds its decoded request, its partially built response, the subscriber chain for its pipeline, and any buffers Netty allocated for the connection — a few tens of kilobytes each, sometimes more if the response body is being assembled.

In the servlet model at most 200 requests are in flight, so that is a few megabytes.

In the reactive model with no limit and a slow pricing dependency, 50,000 requests arrive in ten seconds and all wait, holding perhaps a gigabyte, and the direct buffer pool — off-heap — grows too, which is why the out-of-memory can come from the container rather than the JVM heap.

Netty's PooledByteBufAllocator metrics show the direct memory; the in-flight request count shows the cause. The fix is the same request-level limit: a bounded number of in-flight requests, with the excess rejected quickly. The rewrite did not remove the need for a limit; it removed the limit.

Drill · System design

These prompts test whether you can assemble the primer's patterns into a whole that a team could build, state its trade-offs without being asked, and name the choices you rejected.

Q133 · Design. "Design an order system across four services — order, payment, inventory, shipping — for 500 orders a minute at peak. Show the flow, the data ownership, the consistency model, and the failure handling."

Reveal answer

The real test Whether every pattern from the primer appears in its right place, and whether you say what the customer sees while the system is between states.

Strong answer Requirements: no charge without a shipment or a refund; no shipment without a charge; the customer gets a response in under a second; 500 orders a minute is modest, so correctness beats throughput.

Ownership: order owns orders and the saga state; payment owns charges, refunds, and idempotency keys; inventory owns stock and reservations; shipping owns shipments. Each has its own PostgreSQL and its own outbox.

Flow: the API creates the order in PENDING and writes OrderCreated to the outbox, returning 202 with the order id in about 20 milliseconds; an orchestrator in the order service drives the saga through commands on Kafka, keyed by order id: reserve stock (compensation: release), charge card with the order id as idempotency key (compensation: refund), create shipment (pivot, retry-only), then mark COMPLETED and publish OrderCompleted for notifications and the read model.

Consistency: eventual across services, with the order's status the customer-visible truth and a "My orders" read model fed by events; read-your-writes from the create response.

Failure handling: every consumer idempotent by event id; every step with a deadline and a status query before any compensation; a NEEDS_ATTENTION state with a support queue; breakers and bulkheads on any synchronous call (the pricing lookup at checkout); saga-age metrics and dead-letter alerts.

Trade-offs: the customer sees "processing" for a few seconds rather than an instant confirmation, and there is an orchestrator to operate.

What I would not do: charge synchronously inside the API request, because it turns a payment-provider slowdown into checkout downtime; or share one database "for the transaction", because it recreates the monolith with network hops.

Land it Four owners, one orchestrated saga through outboxes and idempotent consumers, and a customer-facing status that is honest about "processing" — that is the whole design, and everything else is sizing.

Likely follow-ups
"Why is shipment the pivot, and what happens if creating the shipment fails after the charge?"

The pivot is the step after which compensation is no longer acceptable — the point of no return. Before the shipment exists, everything can be undone cleanly: a reservation is released, a charge is refunded.

Once a shipment is created, a parcel may physically leave, and undoing that is a returns process, not a compensation. So the saga puts the reversible steps first, in order of cost to undo, and the irreversible one last.

If creating the shipment fails after the charge, the saga does not compensate; it retries, because the failure is almost certainly transient — the shipping service was slow — and the customer has paid and holds stock.

The retry continues with backoff for a bounded time, say an hour, with the order in a SHIPMENT_PENDING state visible to support. If it still fails, the saga moves to NEEDS_ATTENTION and a human decides: usually create the shipment manually.

A refund at that point is a business decision, not an automatic compensation.

"The requirement changes: the customer must see 'confirmed' with a charge in under a second, not 'processing'. What changes?"

The charge moves into the synchronous path, and I make that safe rather than refuse it.

The API now does: reserve stock synchronously through inventory's conditional decrement, then call payment to authorise — not capture — with the order id as the idempotency key and a 700-millisecond timeout, then commit the order as CONFIRMED with the authorisation id and write the event.

Capture, shipment, and the rest still run as the saga afterwards; an authorisation is reversible for days, so the pivot has not moved.

What I add for the new risk: a payment-provider slowdown now directly slows checkout, so the payment call has a breaker with a fallback that returns "we will confirm by email" — the old asynchronous path — when the provider is degraded; and the reservation has a short expiry so a timeout on payment releases stock automatically.

Under a second at p99 is achievable if the provider's p99 authorisation is under 500 milliseconds, which I would measure before promising.

"How do you handle a saga step whose response is lost — the charge command timed out?"

With a query before any decision, because a timeout means unknown, not failed. The orchestrator, on a timeout of the charge command, does not retry blindly and does not compensate; it asks payment GET /payments?idempotencyKey=order-123 and gets one of three answers.

Succeeded: record the charge id and proceed. Failed: proceed to compensation of the reservation. In progress or unknown: wait with backoff and ask again, up to a deadline.

Only if the deadline passes with no answer does the saga go to NEEDS_ATTENTION, because refunding a charge that may not exist and re-charging one that may exist are both wrong.

The idempotency key is what makes this safe: even if the orchestrator does retry the charge command, payment returns the stored result rather than charging twice.

And the status query has to be cheap and reliable, which means payment keeps the intent row and indexes the key — that is the design of the next question.

"What would you cut under time pressure?"

The orchestrator as a separate component, the read model, and the NEEDS_ATTENTION tooling — but not the outbox, the idempotency, or the ownership split.

In a first version the saga lives in the order service as a state machine over the order row itself, driven by a scheduled poller that advances each order through its steps by calling the other services' APIs synchronously with timeouts and idempotency keys, and marks the state after each.

That is an orchestrator without a framework, and it is a few hundred lines. "My orders" reads the order service's own table directly. Stuck orders are found by a query on state age, and support looks at them in a database tool.

What I keep no matter what: each service owns its data; every cross-service effect goes through the outbox or an idempotent call; and the charge carries the order id as its key. Those three are what make the rest addable later without a migration.

"What breaks at ten times the scale — 5,000 orders a minute?"

At 5,000 a minute — about 80 a second — the design holds but its sizing changes. The orders table grows by seven million rows a day and needs partitioning by month with an archival policy.

The outbox poller's batch and the number of relay instances need to keep up with 80 events a second plus the saga's command events, which is still modest for Kafka but needs the per-row published flag and partial index from the earlier question, or the table becomes the bottleneck.

The saga's synchronous pricing call at checkout is now 800 product lookups a second, which pricing serves from its cache.

Inventory's hot rows — a popular product at 80 reservations a second — approach the lock-convoy point, and the bucket sharding from the ticketing question becomes relevant for a few items.

The orchestrator needs to be horizontally scaled with partitioned ownership of sagas, and at that point Temporal earns its cost. Nothing changes in the flow; everything changes in the numbers.

Q134 · Design. "Design the payment service itself: the charge API, its idempotency, the ledger, provider webhooks, and reconciliation."

Reveal answer

Strong answer Requirements: a charge is attempted at most once per order; every movement of money is recorded before it is acknowledged; the provider's asynchronous outcomes are applied exactly once; the books balance every day.

Design: POST /payments requires an Idempotency-Key; the service inserts the key with state IN_PROGRESS in the same transaction as a payment_intent row, commits, then calls the provider with the same key forwarded (Stripe and Adyen accept one), so a retry on either side cannot double-charge.

The provider's synchronous reply updates the intent; the final result is stored with the key and returned on any repeat.

The ledger is append-only double-entry: every charge, refund, fee, and payout is two entries that sum to zero, in a table that is never updated, only inserted; balances are derived.

Provider webhooks (charge succeeded, disputed, refunded) arrive with a signature that is verified, are stored raw with their provider event id as a unique key so redelivery is a no-op, and are then applied by a consumer that updates the intent and the ledger and writes a PaymentCompleted or PaymentFailed event to the outbox.

A daily reconciliation pulls the provider's settlement report and matches it against the ledger, alerting on any unmatched entry; that job is how every silent bug is found.

Trade-offs: the ledger doubles the write volume and the reconciliation needs the provider's report API. What I would not do is update a balance column in place, or trust the synchronous reply as final — the webhook is the truth for money.

Land it Idempotency at the door, an append-only ledger inside, webhooks as the source of truth, and a reconciliation that runs every day — a payment service is a bookkeeping system with an API on top.

Likely follow-ups
"Walk me through what happens when the same Idempotency-Key arrives twice at the same instant."

Both requests try to insert the key row, and the database's unique constraint decides. The first insert succeeds and that request proceeds to call the provider.

The second insert fails with a unique violation; the handler catches it, reads the existing row, and finds state IN_PROGRESS with no result yet. It cannot return the result because there is none, and it must not call the provider.

So it returns a 409 with a Retry-After: 1 — Stripe does exactly this — and the client retries in a second and gets the stored result.

The alternative is to have the second request wait on the row, but that ties up a thread for the provider's latency and complicates timeouts.

The important detail is that the key row's insert and the payment intent's insert are in the same transaction, so a crash after the insert leaves an IN_PROGRESS row that a sweeper resolves by querying the provider with the same key.

The unique constraint is the whole concurrency control; there is no lock service.

"Why append-only double entry? A balance column is simpler."

Because a balance column has no history and no check.

With a balance, a bug that adds a refund twice leaves a wrong number and nothing to compare it with; with entries, the wrong number is visible as two refund entries against one charge, and the balance is recomputed from entries that are still correct.

Double entry adds the invariant that every transaction's entries sum to zero — a charge is a debit to the customer's receivable and a credit to revenue; a payout is a debit to cash and a credit to the provider's clearing account — so a bug that inserts half a transaction is caught by a nightly check that sums every transaction.

Append-only means an entry is never updated or deleted; a correction is a new reversing entry, so the audit trail is complete, which is what an auditor asks for first.

The cost is that "what is the balance" is a sum, so a materialised balance table is kept as a cache, rebuilt from entries, never written directly by business logic.

"How do you verify a provider webhook, and what if their signature scheme is weak?"

The provider signs the raw request body with a shared secret — Stripe's Stripe-Signature header carries a timestamp and an HMAC-SHA256 over the timestamp and body — and the service recomputes the HMAC over the exact bytes received, before any JSON parsing, and compares in constant time.

The timestamp is checked against a five-minute window to defeat replay. The raw body matters: a framework that parses and re-serialises the JSON before signing will compute a different hash.

If a provider offers only a weak scheme — a shared token in a query string, or no signature — I do not trust the webhook's contents at all; I treat it as a hint and call the provider's API to fetch the event by id, which is authenticated by my credentials, and act on what the API returns.

That fetch-on-webhook pattern is also a good default for any provider, because it makes the webhook idempotent and tamper-proof at the cost of one extra call.

"What does the daily reconciliation actually compare, and what is the most common discrepancy?"

It pulls the provider's settlement report — every charge, refund, fee, and payout they processed for the day, with their ids — and matches each line to a ledger entry by provider id.

Three sets result: matched, in the provider's report but not the ledger, and in the ledger but not the report.

The most common discrepancy is the first mismatch: a charge the provider completed whose webhook was never applied — delivered to a pod that was restarting, or rejected by a bug, or never sent — so the ledger has an intent with no completion.

The fix is to apply it from the report, and the count of those per day is the health metric for the webhook path.

The second most common is fee mismatches, where the provider's fee differs from the estimate the ledger recorded; those are corrected with an adjusting entry. Anything in the ledger and not in the report is serious and is investigated the same day.

The report is the only external truth the service ever sees, so the job never gets skipped.

"What would you cut under time pressure?"

The double-entry ledger's full chart of accounts and the automated reconciliation — but not the idempotency key or the webhook handling.

A first version has the payment intent table with the key, the provider call with the key forwarded, and the webhook handler with signature verification and the unique provider event id, because those are what prevent double charges and lost completions, and they are a few days of work.

The ledger in version one is a single append-only table of money movements with a type, an amount, and the intent id — not double entry, but never updated — which can be migrated into proper entries later without losing history.

Reconciliation in version one is a weekly manual comparison of counts and totals against the provider's dashboard, by a person, until the report API is integrated.

What I would never ship without is the idempotency key, because a duplicate charge is the one bug that costs trust immediately.

Q135 · Design. "Migrate a monolith to services using the strangler fig pattern. Show the mechanics, the order, and how you keep it reversible at every step."

Reveal answer

Strong answer The strangler fig pattern grows the new system around the old one, routing traffic capability by capability until the old one is empty, named after the vine that surrounds a tree.

Requirements: no big-bang cutover; every step reversible with a config change; the business sees continuous delivery throughout.

Mechanics: put a routing layer — the API gateway — in front of the monolith on day one, so every request passes a point where it can be redirected; nothing else changes yet.

Then, per capability: build the new service; give it its own data, fed initially by change data capture from the monolith's tables so it stays current without touching the monolith's code; run it in shadow, receiving a copy of production requests and comparing its responses to the monolith's (a diffing proxy) until the diff rate is zero; switch reads to it with a gateway rule at 1%, then more; then switch writes, with CDC reversed so the monolith's remaining readers still see the data; then delete the monolith's code for that capability.

Order: start with something at the edge with few callers inward — notifications, search — to prove the tooling; leave the deeply shared core — the customer model — for last, because it is what everything else depends on.

Reversibility: every switch is a gateway rule or a flag, the old path stays until the new one has run for weeks, and the CDC keeps the old tables current so switching back loses nothing. Trade-offs: months of dual running and CDC plumbing.

What I would not do is freeze the monolith; features keep landing there for capabilities not yet moved, or the migration loses its business support.

Land it A gateway in front, capture underneath, shadow before switch, and the old path alive until the new one has earned it — the strangler is a sequence of reversible steps, not a project with a cutover date.

Likely follow-ups
"What does the diffing proxy do with responses that legitimately differ — timestamps, ids, ordering?"

It normalises before comparing, with rules per endpoint.

The proxy sends each request to the monolith and to the new service, returns the monolith's response to the caller, and compares the two bodies after applying a normaliser: fields named in an ignore list — generatedAt, requestId — are dropped; arrays declared as unordered are sorted by a key; floating-point values are compared with a tolerance; and the new service's ids are mapped through a translation table where the id schemes differ.

What remains after normalisation must match, and mismatches are logged with both bodies and grouped by a hash of the diff shape so that one bug appears as one group rather than ten thousand lines.

The first week of shadowing is mostly tuning the normaliser; after that, every new diff group is a real behavioural difference to investigate. GitHub's Scientist library is the in-process version of this idea, and a proxy such as Diffy is the out-of-process one.

"How does CDC reversed work when you switch writes to the new service — and isn't bidirectional sync dangerous?"

It is dangerous if both directions run at once, so they never do. Before the write switch, CDC flows from the monolith's tables to the new service's store, and the new service is read-only for that data.

At the switch, the flow reverses: the new service becomes the writer, and a consumer of its events writes back into the monolith's tables so that the monolith's remaining code — reports, other modules not yet migrated — still sees current data.

The monolith's own writes to those tables are disabled by the same switch, usually by routing the write endpoints to the new service and by removing the monolith's write paths behind a flag.

There is a moment at the switch where in-flight writes could land on both sides, and I handle it with a brief write pause — seconds — while the forward CDC drains, then flip.

The reverse sync is temporary and is removed when the last monolith reader of those tables is migrated, which is when the capability is truly done.

"Which capability first, and how do you know the order is right?"

First is something with clear edges, few callers, and low risk: notifications or search are the usual choices, because they are read-heavy, they have one obvious input, and if the new service is wrong the damage is a missed email, not a wrong charge.

The purpose of the first one is to build the machinery — the gateway rule, the CDC pipeline, the shadow proxy, the switch procedure — and find its problems on something forgiving.

Then capabilities in order of business value divided by coupling: a capability that many others depend on is expensive to move and should go late, because every dependent must be repointed. The core customer model is last for that reason.

The order is right if each step is independently reversible and each delivers something the business notices — a faster search, a notification channel the monolith could not support — because a migration that delivers nothing visible for a year loses its sponsor.

"What would you cut under time pressure?"

The shadow-diff phase for low-risk capabilities and the reverse CDC where the monolith has no remaining readers. For notifications, shadowing is overkill — switch 1% of traffic and watch the metrics, which is the canary doing the same job with less machinery.

Reverse CDC is only needed when the monolith still reads the moved data; for a capability whose data nobody else touches, skip it and accept that switching back means a short data backfill.

What I do not cut is the gateway in front on day one — it costs a day and it is the precondition for every reversible step — and the rule that the monolith is not frozen, because a frozen monolith is the fastest way to lose the business's patience.

If the pressure is to show progress, I pick a capability that ships a visible improvement in the first month, even if it is not the architecturally ideal first choice.

Q136 · Design. "Design a notification platform for the whole company: email, SMS, push, in-app; 50 million notifications a day; preferences, templates, rate limits, and no duplicates."

Reveal answer

Strong answer Requirements: any service can request a notification with one call or event; the user's preferences and legal opt-outs are enforced centrally; a provider outage delays rather than loses; no user gets the same notification twice; 50 million a day is about 600 a second average and perhaps 5,000 at peak.

Design: producers publish a NotificationRequested event with a caller-supplied idempotency id, a template id, a user id, and payload — never a rendered message.

An ingest consumer deduplicates on the idempotency id (guard table with a 7-day window), loads the user's preferences and consent (a local copy fed by the preferences service's events), decides channels, applies per-user rate limits and quiet hours, renders the template, and writes one delivery row per channel with state QUEUED, plus a command to that channel's topic.

Channel senders — one service per channel — consume with bounded concurrency matched to each provider's rate limit, call the provider with the delivery id as its idempotency reference, and record the result; provider webhooks (delivered, bounced) update the delivery and feed an analytics stream.

Failures: bounded retries with backoff per provider, a dead-letter topic per channel with an owner, breakers per provider, and a secondary provider for email and SMS switched by flag. Priority topics (transactional above marketing) so a marketing blast never delays a password reset.

Trade-offs: a central platform is a single team every other team depends on; its API must therefore be tiny and stable.

What I would not do is let each producer call providers directly, which is how a company ends up with eleven SMS contracts and no opt-out enforcement.

Land it One event in, preferences and dedup at the door, a sender per channel with the provider's limits and a fallback, and transactional traffic on its own lane — the platform's value is that no one else has to think about any of that.

Likely follow-ups
"Where does the idempotency id come from, and what stops two producers generating the same one for different notifications?"

The producer builds it from the business event that caused the notification, not from a random value, so that a retry of the same cause yields the same id: order-shipped:order-12345, or for a scheduled reminder, cart-reminder:customer-9:2026-08-28.

That is what makes "no duplicates" true across producer retries and replays, because a random UUID per attempt would be unique every time and deduplicate nothing.

Collisions between producers are prevented by namespacing: the id is prefixed with the producing service's name, and the platform rejects an event whose prefix does not match the caller's identity from the mesh.

The guard table is keyed on the full id with a seven-day window, indexed, and the insert-or-ignore happens in the same transaction as the delivery rows, so a crash between them cannot produce a duplicate later.

The window is a trade-off: longer catches slower replays but grows the table; seven days at 50 million a day is 350 million rows, which is fine with a partitioned table pruned daily.

"How do you enforce a provider's rate limit across many sender pods without a central bottleneck?"

By making the partition count the concurrency control. The email sender consumes from a topic with, say, 16 partitions, one consumer pod per partition, and each pod sends at a fixed maximum rate — the provider's limit divided by 16 — using a local token bucket.

The total never exceeds the limit because the number of senders is bounded by the partition count and each one's rate is bounded locally, with no shared counter.

If the provider returns 429 anyway, the pod backs off and the record is retried in place, which is acceptable here because ordering within a channel is not required.

For providers with very low limits or per-account quotas, a single sender pod with a larger batch is simpler than coordination.

The metric to watch is the provider's 429 rate and the topic's lag; a growing lag with no 429s means the limit is set too conservatively, and I raise the per-pod rate.

"The requirement changes: a notification must arrive within thirty seconds of the event or not at all. What changes?"

A time-to-live on every delivery, enforced at the sender. The delivery row carries a send_by timestamp computed from the event time plus thirty seconds; the sender checks it before calling the provider and, if it has passed, marks the delivery EXPIRED without sending, emitting a metric.

That prevents a backlog from delivering a "your driver is arriving" push an hour late, which is worse than nothing.

The consequence is that lag is now a correctness problem, not just a latency one, so the transactional priority lane needs headroom — capacity for three times its normal rate — and an alert when its lag exceeds ten seconds, well before the thirty.

Retries for that class are short: two attempts within the window, then expire.

For channels where the provider itself queues — SMS carriers can take minutes — I pass the TTL to the provider where the API supports it, and otherwise accept that the guarantee ends at handover.

"What would you cut under time pressure?"

The secondary providers, the analytics stream, and the per-user rate limits and quiet hours, in the first release — but not the dedup, the preferences check, or the priority lanes.

A first version takes the NotificationRequested event, deduplicates, checks the user's opt-outs against a local copy of preferences, renders, and sends through one provider per channel with bounded retries and a dead-letter topic, with transactional and marketing on separate topics so a blast cannot delay a password reset.

That is the legal minimum — opt-outs enforced — and the operational minimum — no duplicates, no head-of-line blocking. Quiet hours and per-user limits come second because their absence annoys users but does not break the law or lose money.

The secondary provider comes when the first provider has its first outage, which will be soon, and the analytics stream comes when marketing asks for open rates.

What I would not skip is the guard table, because "we sent it twice" is the complaint that reaches the CEO.

Q137 · Design. "Design a rate limiter that enforces per-client limits correctly across twelve gateway instances, with bursts allowed and no single point of failure."

Reveal answer

Strong answer Requirements: a limit of N requests per minute per client means N across all instances, not N per instance; short bursts are tolerated; the limiter's own failure must not take the gateway down; the decision must cost well under a millisecond.

Design: a token bucket per client — a bucket of capacity B (the burst) refilled at rate R per second — stored in Redis, with the check-and-consume done by a Lua script so it is atomic across instances: read tokens and last-refill time, add refill, if at least one token remains subtract and return allowed, otherwise return the wait time.

Keys expire after inactivity.

Each gateway instance keeps a small local cache of recent decisions for clients far below their limit, so most requests never touch Redis, and consults Redis only near the limit — a two-tier design that keeps the shared store's load proportional to clients near their cap.

Failure: Redis calls have a 5-millisecond timeout and a breaker; on failure the gateway falls back to a local, per-instance bucket of N divided by the instance count, which is conservative but keeps serving.

Redis itself runs as a cluster with replicas; the limiter tolerates brief inconsistency during failover, since a few extra requests are acceptable and a few extra rejections are not harmful. Responses include RateLimit-Remaining and Retry-After. Trade-offs: slight over-admission during Redis failover and slight under-admission in fallback.

What I would not do is a fixed window, which admits twice the limit at a boundary, or a limiter that fails closed and takes the API down with the cache.

Land it An atomic token bucket in a shared store, a local tier for the common case, and a conservative local fallback when the store is gone — correct when it matters, cheap when it does not, and never the reason the gateway is down.

Likely follow-ups
"Write out the Lua script for the token bucket and explain why it has to be a script."

In outline the script takes the key, the capacity, the refill rate per millisecond, the current time in milliseconds, and the tokens requested. It reads two fields from a hash — tokens and ts — with HMGET; if absent, it starts with a full bucket.

It computes elapsed time since ts, adds elapsed times rate to tokens, capped at capacity.

If tokens are at least the requested amount, it subtracts, writes both fields back with HSET, sets an expiry of about twice the time to refill from empty, and returns 1 plus the remaining tokens; otherwise it returns 0 plus the milliseconds until enough tokens exist.

It has to be a script because the read, the arithmetic, and the write must be atomic across twelve gateway instances: two instances reading 1 token left at the same moment would both admit.

Redis runs a script without interleaving other commands, so EVALSHA gives that atomicity in one round trip, under a millisecond.

"The local decision cache — how does it stay correct if the client's requests are spread across instances?"

It does not try to be exact; it only short-circuits the cases where exactness cannot matter. Each instance keeps, per client, the last result from Redis and its timestamp.

If that result said the client had, for example, 900 of 1,000 tokens remaining, the instance knows that even if every one of the twelve instances admitted requests at the client's observed rate, the bucket cannot be empty within the next few hundred milliseconds, so it admits locally and counts, and consults Redis again when its local estimate drops below a safety margin — say 20% of capacity — or after a fixed interval.

The estimate is conservative: it assumes all twelve instances are consuming at the same rate, so it errs toward calling Redis too soon rather than admitting too much.

Clients near their limit therefore always go to Redis and get the exact answer; clients far from it are served from the local tier. That keeps Redis load proportional to the number of clients near their cap.

"How do you test that the limiter is correct under concurrency?"

With a test that hammers one key from many threads and counts what was admitted.

Against a Testcontainers Redis, a JUnit test starts fifty threads that each make a hundred requests for the same client as fast as possible, with a bucket of capacity 200 and a refill of 100 per second, and collects the admitted count over exactly two seconds.

The correct answer is bounded: at most capacity plus refill times elapsed, so at most about 400, and at least close to that if the threads are fast enough.

A fixed-window bug shows up as a burst admitting far more; a race in a non-atomic implementation shows up as an over-admission of a few percent that varies run to run.

A second test asserts that the wait-time hint returned on rejection is accurate by sleeping that long and expecting admission. And a third test kills the Redis container mid-run and asserts that the fallback engages within the breaker's window and admits at the reduced local rate.

"What would you do differently in a greenfield design — is Redis the right store?"

In a greenfield design with a mesh already present, I would look hard at the mesh's global rate limiting before building anything: Envoy's rate limit service with its own Redis backend implements exactly this — per-descriptor buckets, atomic counting, headers — and the gateway is often Envoy-based.

That removes the code and keeps the behaviour.

If building, Redis stays the right choice for the shared tier because the operation is a sub-millisecond atomic read-modify-write on tiny values, which is what Redis is good at, and the data is disposable — losing the buckets on a failover means a few clients get a fresh bucket, which is harmless.

I would not use a database, which is too slow per decision, nor a consensus store like etcd, whose durability is wasted here and whose latency is too high.

What I would add from the start is the local tier, because most limiter designs skip it and then discover that Redis is on the critical path of every request.

Q138 · Design. "Design an inventory service for scarce stock — concert tickets — where overselling is not acceptable. Cover reservations, expiry, concurrency, and the API."

Reveal answer

Strong answer Requirements: never sell more units than exist; a customer holds a reservation for a bounded time while paying; thousands of concurrent attempts on the same item at on-sale time.

Design: the truth for each item is one row with available and a version, in PostgreSQL; a reservation is a conditional decrement in a single statement — UPDATE stock SET available = available - ? WHERE sku = ? AND available >= ? — which is atomic under any isolation level (see Chapter E8) and returns zero rows when stock is short, so no read-then-write race exists.

Each reservation is a row with an expiry; a sweeper releases expired ones by adding back to available in the same transaction that marks them expired. Confirmation (after payment) flips the reservation to sold and never touches available again.

Concurrency at on-sale time: the hot row becomes a lock convoy at thousands of updates a second, so for the very hottest items I shard the stock into buckets (ten rows of a tenth each), route attempts to a bucket by hash, and fall back to the other buckets on zero — the same stock, less contention; a queue in front (a virtual waiting room) is the honest answer for a stadium on-sale.

API: POST /reservations with an idempotency key returns the reservation and its expiry; POST /reservations/{id}/confirm; DELETE to release. Events on each transition go through the outbox for the order saga. Trade-offs: the synchronous reservation call is on the checkout's critical path by necessity here.

What I would not do is a Redis counter as the truth, because a Redis failover can lose decrements and sell seats twice.

Land it One conditional decrement as the truth, reservations with expiry, buckets for the hottest rows, and a queue when even that is not enough — scarcity is the case where the database's atomicity is the feature, not the bottleneck.

Likely follow-ups
"How exactly does the bucket sharding work when a bucket runs out and others still have stock?"

The stock for one item is spread over ten rows — stock_bucket(sku, bucket, available) — each holding a tenth.

A reservation hashes the request's idempotency key to a bucket and runs the conditional decrement on that row; if it updates zero rows, the bucket is empty, and the code tries the next bucket in a fixed rotation, up to all ten, before declaring the item sold out.

Contention drops by roughly ten because concurrent attempts spread across ten row locks. The cost is the last few units: when nine buckets are empty and one has two units, most attempts hit an empty bucket first and pay a few extra statements, which is fine.

Releases go back to the bucket the reservation came from, recorded on the reservation row. The total available is the sum across buckets, a cheap query for display.

For most items a single row is enough; sharding is turned on per item by a flag when the reservation rate is expected to exceed a few hundred a second.

"Describe the expiry sweeper precisely and the race it has with a customer confirming at the same moment."

The sweeper runs every few seconds and does, in one transaction, UPDATE reservation SET status='EXPIRED' WHERE status='HELD' AND expires_at < now() RETURNING sku, bucket, qty, then adds the returned quantities back to the stock rows, and commits — using SKIP LOCKED and a batch limit so many sweeper instances do not block each other.

The race: the customer's confirm arrives at the same moment. Confirm does UPDATE reservation SET status='SOLD' WHERE id=? AND status='HELD'.

Whichever statement takes the row lock first wins, and the other updates zero rows: if the sweeper won, confirm sees no row updated and returns "reservation expired, please try again", and the stock is already back; if confirm won, the sweeper's WHERE status='HELD' excludes it.

There is no window in which both succeed, because both are conditional updates on the same row under the database's row lock.

The customer-facing rule that follows is a small grace — the sweeper uses expires_at + 5 seconds — so a confirm that arrives on the deadline is not unlucky.

"The requirement changes: seats are assigned, not just counted. Does the conditional decrement still work?"

The principle holds, but the unit changes from a count to a row per seat. Each seat is a row with a status; a reservation of specific seats is UPDATE seat SET status='HELD', reservation_id=? WHERE id IN (...) AND status='AVAILABLE', and it succeeds only if the updated row count equals the number of seats requested — otherwise the transaction rolls back, because a partial hold of three of four seats is not what the customer asked for.

Deadlocks between two customers taking overlapping sets are avoided by ordering the seat ids in every statement. "Best available" is a select of candidate seats followed by the conditional update, retried on a short miss.

Contention concentrates on the best seats rather than on one counter row, which is naturally spread, so bucket sharding is not needed, but the on-sale surge still wants the waiting room. Expiry is the same sweeper over HELD seats.

The API changes to return seat identifiers, and the idempotency key protects the whole set.

"What would you cut under time pressure?"

The bucket sharding and the waiting room, not the conditional decrement or the expiry.

A first version with a single stock row per item, the atomic decrement, reservations with expiry, and the sweeper is correct — it never oversells — and it handles hundreds of reservations a second on a modest database, which is more than most on-sales need.

The failure mode under a real surge is that it gets slow, with a lock convoy on the hot row, and slow is acceptable for a first release where wrong is not.

Sharding is added per item when a specific sale is expected to exceed that, and it is a schema addition and a code path, not a redesign.

The waiting room is a product feature and comes when the business schedules a sale big enough to need it.

What I would not skip is the idempotency key on the reservation API, because the retry of a timed-out reservation is exactly the request that oversells without it.

Q139 · Design. "Design the edge for a platform with a web app, an iOS app, and partner APIs: where does the gateway end and the backend-for-frontend begin?"

Reveal answer

Strong answer Requirements: one place for authentication, rate limiting, and routing; screens that need data from several services without the client making five calls; partner APIs that are stable for years while the apps change weekly. Design in two layers.

The gateway is one, shared, and dumb about the domain: TLS, token validation, rate limits, routing by host and path, request logging with a trace id.

Behind it, one backend-for-frontend (BFF) per client type — a web BFF and a mobile BFF — each owned by the team that owns that client.

The BFF composes screens: the mobile home screen is one call that fans out concurrently to orders, recommendations, and promotions with timeouts and fallbacks, and returns a payload shaped for that screen, small enough for a phone.

The BFF changes as often as the app, and it may lie about shape for the app's convenience, because it has exactly one consumer.

The partner API is not a BFF: it is a versioned, documented, contract-tested product owned by a platform API team, with long deprecation windows and no screen-specific shapes.

Trade-offs: BFFs duplicate some composition logic across web and mobile, which is accepted because their needs differ; the gateway must stay domain-ignorant or it becomes a bottleneck.

What I would not do is a single "aggregation layer" shared by all clients — it becomes a service everyone changes and nobody owns — or GraphQL for the partner API, where a stable contract matters more than flexibility.

Land it A shared dumb gateway, a BFF per client owned by the client's team, and a partner API treated as a product — three layers with three different rates of change.

Likely follow-ups
"What does the mobile BFF's fan-out look like with timeouts and fallbacks, in code shape?"

The home-screen handler forks three calls — orders, recommendations, promotions — concurrently, each through its own client with its own timeout and fallback, then assembles whatever came back.

With virtual threads and structured concurrency: open a StructuredTaskScope, fork the three subtasks, joinUntil a deadline of 400 milliseconds, and read each subtask's result or, if it failed or is still running, its fallback: an empty recommendations list, no promotions banner, and for orders — the one the screen cannot do without — an error the app shows as a retry.

The response carries a per-section status so the app can render partial content and refetch a section, which is better than an all-or-nothing screen.

Each client has a breaker, so a dependency that has been slow for a minute is skipped immediately rather than timed out every time.

The trace shows the three spans side by side under the BFF span, which is how I verify the fan-out is actually parallel.

"Why not GraphQL as the BFF? It solves the composition problem generically."

It can, and for the web and mobile BFFs I would consider a GraphQL layer owned by the client team, because the client decides what it needs per screen and the schema evolves additively — those are the BFF's requirements.

The costs are the reasons I do not default to it: a GraphQL layer needs the same fan-out, timeouts, and fallbacks under the hood, so it does not remove the resilience work, only hides it in resolvers; N+1 queries appear unless data loaders are written carefully; caching at the CDN is harder with POST bodies; and rate limiting has to be by query cost rather than by endpoint.

For the partner API, no: partners need a stable contract they can generate a client from and that we can version and deprecate field by field, and a schema that lets them ask for anything makes deprecation and capacity planning harder.

So GraphQL for the screens if the client team wants it, REST or gRPC with OpenAPI for partners.

"The web and mobile BFFs duplicate the checkout composition. Doesn't that violate 'don't repeat yourself'?"

It duplicates the composition, not the business logic, and that distinction is the whole design. Checkout's rules — pricing, reservation, payment — live once, in the checkout and payment services, and both BFFs call them.

What each BFF has is its own view: which fields the screen needs, in what shape, with what fallbacks, on what timeout.

Those genuinely differ — the phone wants a small payload and progressive sections, the web wants everything for one render — and sharing them means every change to one screen risks the other.

When the composition is truly identical and stable, the cure is to move it down into the service that owns the data, as a purpose-built endpoint that both BFFs call, rather than to share it sideways in a library.

The rule I use is that duplication between BFFs is acceptable, duplication of a domain rule is not, and a domain rule that has crept into a BFF is a bug.

"What would you cut under time pressure?"

The separate mobile BFF, temporarily: one BFF serving both web and mobile, owned by the larger client team, with the mobile app using a slightly heavier payload than ideal.

The gateway I do not cut, because token validation and rate limiting in one place is the security baseline and takes a day with an off-the-shelf gateway.

The partner API I do not cut either, but I ship it small — three endpoints with an OpenAPI document and a version prefix — because the first partner integration sets the contract that lives for years, and the cost of getting it wrong is higher than a week's delay.

The second BFF splits out when the mobile team's changes start being blocked by the web team's, which is the signal that the shared BFF has become the aggregation layer the design was avoiding.

I would write that split trigger down at the time of the cut.

Q140 · Design. "Design active–passive multi-region for the order platform with a 15-minute recovery time and a 1-minute data-loss window. What has to be true for those numbers to hold?"

Reveal answer

Strong answer Requirements as numbers: recovery time objective (RTO) 15 minutes — the platform serves traffic from the second region within that; recovery point objective (RPO) 1 minute — at most one minute of committed writes may be lost.

Design: the primary region serves all writes; the secondary runs the full set of services warm — deployed, scaled to perhaps a third of capacity, receiving no traffic — because deploying forty services during an incident is how 15 minutes becomes 3 hours.

Each service's database replicates asynchronously to the region, with replication lag monitored and alerted above 30 seconds, since lag is the RPO in practice. Kafka topics are mirrored with MirrorMaker 2, including consumer offsets translated, so consumers resume near where they were.

Failover is one runbook, automated: fence the primary (revoke its database write access and stop its gateway) so it cannot keep accepting writes; promote each database replica; point DNS or the global load balancer at the secondary with a short TTL prepared in advance; scale the secondary up.

Idempotency keys and saga state replicate with everything else, and a reconciliation job runs after failover to find the orders in the lost minute against the payment provider.

What has to be true: the secondary is exercised — a failover drill every quarter, timed; every service is stateless outside its database; no service depends on a resource that exists only in the primary (a cache, a config server, a secrets store); and the fencing step is real, or the split-brain in Q125 follows.

Trade-offs: a warm region costs roughly 40% of the primary continuously. What I would not do is active–active for order writes, which needs conflict resolution the domain does not tolerate.

Land it RPO is replication lag and RTO is a rehearsed runbook — the numbers hold only if the secondary is warm, the primary can be fenced, and someone has actually pulled the switch in a drill.

Likely follow-ups
"Walk me through the failover runbook with times against each step, adding up to under fifteen minutes."

Minute 0 to 2: the decision. The on-call lead confirms the primary region is not recoverable within the recovery time — a checklist of three signals, not a debate — and declares failover in the incident channel. Minute 2 to 4: fence.

A script revokes the application roles' write access on every primary database, sets the primary gateway to 503, and stops the primary's Kafka producers by scaling the outbox relays to zero; each step is verified by a check that returns in seconds.

Minute 4 to 7: promote. The same script promotes each database replica with pg_promote(), in parallel, and MirrorMaker's offset translation is confirmed for the consumer groups. Minute 7 to 9: switch.

The global load balancer's weights move to the secondary, and DNS with its pre-set 60-second TTL follows. Minute 9 to 13: scale. The secondary's deployments scale from a third to full capacity, which takes about four minutes with pre-pulled images.

Minute 13 to 15: verify with the synthetic checkout journey, and open the reconciliation job. Every step has a named owner and a check, and the script is the same one the quarterly drill runs.

"How do consumer offsets survive the failover — what does MirrorMaker 2 actually translate?"
<parsed></parsed>

Offsets are per cluster and do not match across clusters, because the mirrored topic on the secondary has its own offset numbering — a record at offset 1,000 on the primary may be offset 987 on the secondary if some records were compacted or the mirror started later. MirrorMaker 2 keeps a checkpoint topic mapping primary offsets to secondary offsets per consumer group and partition, updated periodically, and its MirrorCheckpointConnector can write the translated offsets into the secondary cluster's consumer group state automatically with sync.group.offsets.enabled=true. On failover, a consumer starting on the secondary with the same group id resumes from the translated offset — close to where it was, possibly a few records behind, which means a small replay that the idempotent consumers absorb. Without that, the consumer would start from earliest or latest, which is either a full replay or a gap. The check I run in the drill is the translated lag per group right after promotion, which should be seconds, not hours.

"The requirement changes: recovery point must be zero for payments. What changes and what does it cost?"

The payment service's database moves to synchronous replication to the secondary region, so a commit is acknowledged only after the standby has written it — PostgreSQL's synchronous_standby_names with synchronous_commit=on for that instance alone.

The cost is the cross-region round trip on every payment commit — 30 to 70 milliseconds between regions on the same continent — which is acceptable for a charge but would not be for the catalogue, so it applies only to payment intents and idempotency keys.

The availability trade-off is that if the standby is unreachable, commits block; I mitigate that with a second synchronous candidate or, less strictly, by allowing an automatic fall back to asynchronous after a timeout with an alert, which reopens a loss window only during a standby outage.

The rest of the platform stays at one minute. This is the version of the earlier failover scenario's lesson: pay the synchronous cost exactly where the data is money and nowhere else.

"What would you cut under time pressure?"

The warm secondary's compute, not its data.

A cold secondary — databases replicating, Kafka mirrored, images in the registry, manifests ready, but zero pods running — cuts the ongoing cost to the replication and storage and turns the recovery time from fifteen minutes into perhaps forty-five, because forty services have to be deployed and scaled.

That is a real change to the objective, and I would get it agreed rather than slip it in.

What I do not cut: the replication and its lag monitoring, because that is the recovery point and it cannot be added retroactively for data already lost; the fencing script, because the split-brain scenario is worse than a slow failover; and the drill, at least once before anyone relies on the number.

A failover plan that has never been run has an unknown recovery time, whatever the document says. The warm compute comes back when the business signs off on the fifteen-minute objective as a requirement with a budget.

Q141 · Design. "A flash sale will bring 20× normal traffic for ten minutes. Design the platform's response so that checkout survives and no one is charged for stock they do not get."

Reveal answer

Strong answer Requirements: the sale page loads for everyone; checkout serves as many as capacity allows, fairly; excess demand waits rather than fails; inventory is never oversold. Design in layers.

At the CDN: the sale pages and product data are fully cached with short TTLs and pre-warmed, so the 20× read traffic never reaches the platform.

At the edge: a virtual waiting room — visitors get a queue token and a position, and the gateway admits token holders into checkout at a rate matched to the platform's tested capacity (say 400 checkouts a minute), which converts a spike into a controlled flow and is honest with users about the wait.

Inside: pre-scaled services (autoscaling is too slow for a ten-minute event), with load shedding by priority so in-progress checkouts finish before new ones start; the inventory reservation as the atomic conditional decrement with a short expiry, so a reservation is taken before payment and released if payment is abandoned — the guarantee that nobody pays for stock they do not hold; payment through the saga with idempotency keys; and every non-essential dependency (recommendations, reviews) behind a flag turned off for the sale.

Observability: a war-room dashboard of admission rate, checkout success, reservation conflicts, and payment latency, with the admission rate as a live dial. Rehearsal: a load test at 20× the week before with the same configuration.

Trade-offs: the waiting room is a product decision and costs some conversions. What I would not do is rely on retries and autoscaling; the first amplifies and the second arrives after the sale is over.

Land it Cache the reads away, admit the writes at a rate you have tested, reserve before charging, and rehearse — a flash sale is won in the week before, not on the day.

Likely follow-ups
"How does the virtual waiting room work mechanically — where is the state and how is the admission rate applied?"

The waiting room sits at the edge, usually in the CDN's compute layer or a small stateful service behind it.

A visitor arriving at the sale page without an admission token is given a queue position from an atomic counter and a signed cookie carrying that position; the page polls every few seconds asking whether its position is below the current admission marker.

The marker advances at the configured rate — 400 a minute means it moves by about seven every second — driven by a single controller that also reads live checkout latency and can slow down.

When a position is admitted, the poll returns a signed admission token valid for, say, ten minutes, and the gateway lets requests bearing a valid token into checkout; everything else gets the waiting page.

The state is two numbers — next position and admission marker — in Redis or in the CDN's key-value store, which is why it scales; nobody's individual position needs to be stored, only the counter and the marker.

Managed versions exist from the major CDNs, and I would use one before building it.

"How much do you pre-scale, and how do you know?"

From the load test, and to the admission rate rather than to the raw traffic.

Twenty times normal traffic is what arrives at the CDN and the waiting room; what reaches checkout is the admission rate I chose, which I set at 80% of the capacity the load test showed for checkout, payment, and inventory together.

Pre-scaling means those services run at the pod count that the load test needed for that rate, plus a margin of 50%, from an hour before the sale until an hour after, with the autoscaler's minimum raised so it cannot scale down mid-event.

The catalogue and the product service scale for the CDN's origin misses, which the pre-warm keeps small.

The databases are the constraint that cannot be pre-scaled quickly, so their connection pools and the bulkheads in front of them are what the admission rate is really sized against.

I know it is right when the rehearsal at 20× the week before holds p99 within the SLO at the admission rate with the margin unused.

"The fix didn't work — you rehearsed at 20× and on the day checkout still slowed. What did the rehearsal miss?"

Usually one of three things. Real traffic has a shape the load test did not: all the demand is on one product, so the inventory hot row saw contention the test spread across many products — the bucket sharding was needed for that one item.

Or a dependency outside the test — the payment provider — slowed under everyone else's sale-day load, which a load test against a sandbox cannot reproduce; the breaker and the "confirm by email" fallback are the answer, and the war-room dial is turning the admission rate down.

Or a feature that was supposed to be flagged off was not, and recommendations or reviews consumed capacity the test did not include.

The diagnosis on the day is the war-room dashboard — reservation conflicts, payment latency, and per-dependency latency — and the fix on the day is the admission dial.

Afterwards, the load test is changed to use the real traffic shape captured from the sale, single hot product included.

"What would you cut under time pressure?"

The custom waiting room and the war-room dashboard, but not the admission limit, the reservation-before-charge, or the pre-scaling.

Without a waiting room, the gateway's rate limit at the tested capacity returns a static "we are busy, try again in a moment" page with a random retry delay — less fair and less polished, but it protects checkout, and it is configuration.

Reservation before charge is already how the inventory service works, so it costs nothing to keep and it is the guarantee that nobody pays for stock they do not get. Pre-scaling is a change to the deployment's replica count.

The dashboard is replaced by the existing service dashboards open in four tabs.

What I would insist on even in a week is one load test at the planned admission rate, because a number that was never tested is a guess, and turning off the non-essential features by flag, because that is a five-minute change with a large effect.

Q142 · Design. "Design a search and listing service for the storefront that combines data from catalogue, pricing, inventory, and reviews, updated within seconds of a change."

Reveal answer

Strong answer Requirements: full-text and faceted search over millions of products; each result shows price, availability, and rating; changes from any of four services appear within a few seconds; the four owning services take no read load from search.

Design: a search service owns an OpenSearch or Elasticsearch index with one document per product carrying the fields from all four sources.

It builds the index by consuming events: ProductChanged, PriceChanged, StockChanged (batched, because stock changes constantly), and ReviewAggregated (a rating summary the reviews service publishes hourly, not each review).

Each consumer is idempotent and does a partial document update keyed by product id, using the index's versioning with the event's sequence so an older event cannot overwrite a newer one when partitions deliver out of order.

Availability is stored coarsely (in stock, low, out) to keep update volume manageable, and checkout re-checks the true count.

Rebuild: a versioned index name with an alias, so a projection bug is fixed by building a new index from a replay and switching the alias — never by patching in place.

Queries go only to the search service; the storefront calls it with a timeout and a cached fallback of the last result for the same query. Trade-offs: a few seconds of staleness, and a large denormalised document that must be rebuilt when its shape changes.

What I would not do is have the search service call the four services at query time — four availabilities multiplied on every keystroke — or read their databases through a shared connection.

Land it A read model fed by events with versioned partial updates and an alias for rebuilds — search is the textbook case for CQRS, and its only real difficulty is the field that changes a thousand times a minute.

Likely follow-ups
"How does the version check on a partial update stop an older event from overwriting a newer one?"

Each source keeps its own version per product — a sequence number the producing service increments on every change and puts in the event. The index document stores the last applied version per source: price_version, stock_version, and so on.

The update is a scripted partial update in OpenSearch: the script compares the incoming version with the stored one and applies the fields only if the incoming is greater, otherwise it is a no-op.

Because the update runs atomically on the shard for that document, two consumers applying events for the same product cannot interleave badly.

OpenSearch's external versioning does something similar at the document level, but with four sources contributing to one document, a per-source version inside the document is the correct grain.

The event's version comes from the producer's own row version, so it is meaningful across partitions and replays, which a Kafka offset is not. I test it by replaying a day's events in random order into a scratch index and asserting it equals the in-order result.

"Stock changes a thousand times a minute for popular items. How do you batch without lying to the customer?"

By separating what the listing shows from what checkout checks.

The listing shows a coarse state — in stock, low stock, out of stock — and a change between those states is rare even when the count changes constantly, so the stock consumer only emits an update to the index when the coarse state changes, plus a periodic update at most once every ten seconds per product regardless.

That reduces a thousand updates a minute to a handful. The customer is not lied to because the coarse state is what they are shown and it is accurate within seconds; the exact count they never see on a listing.

At the moment of adding to cart or checkout, the inventory service is asked directly, and that is where the true count applies.

The failure mode to watch is a product flapping between "low" and "in stock" at the threshold, which is fixed with a small hysteresis: go to "low" below 5, back to "in stock" above 10.

"The requirement changes: personalised ranking based on the customer's history. Where does that go?"

Not into the index document, because personalisation is per customer and the index is per product.

The design becomes two stages: the search service retrieves the candidate set from the index using the query and facets, returning perhaps the top 200 by relevance, and a ranking step reorders those 200 using per-customer signals — a small feature vector per customer kept in a fast store, updated by a consumer of browsing and purchase events.

The ranking runs inside the search request with a strict time budget, say 30 milliseconds, and falls back to the index's relevance order if the customer's features are missing or the ranker is slow.

OpenSearch's learning-to-rank plugin or a rescore query can do the reorder inside the engine if the features can be expressed as query parameters.

Caching changes too: results are cacheable by query for anonymous users and not for personalised ones, so the candidate retrieval is cached and only the rerank is per customer.

"What would you cut under time pressure?"

The per-source versioning and the alias-based rebuild tooling, temporarily, in favour of a simpler consistency model: every event triggers a full re-read of that product's data from the four owning services' APIs and a full document replacement.

That is slower and puts read load on the services — the thing the design avoids — but at launch volumes it is fine, it is trivially correct against reordering because the latest read wins, and it is a few days of work instead of weeks.

Reviews and stock come in as their hourly and coarse updates. The alias I would keep even under pressure, because it is a naming convention that costs nothing and makes the first rebuild painless.

What I would defer is the query-time fallback cache and the coarse-stock hysteresis. The versioned partial updates come when the re-read load on the catalogue and pricing services shows on their dashboards, which is the signal the shortcut has expired.

Q143. "Build or buy for platform pieces — a service mesh, a workflow engine, a schema registry, a feature-flag service. What is your decision process?"

Reveal answer

Strong answer I ask four questions in order. Is this piece the company's product or a commodity?

A mesh, a registry, a flag service, and a workflow engine are commodities; nobody's customers care which one you run, so the default is to adopt the mature open-source or managed option and spend engineers on the product.

What is the total cost of owning it — not building it, owning it: upgrades, on-call, the person who leaves with the knowledge? A home-built saga orchestrator is a weekend to write and a career to maintain.

What is the cost of the wrong choice, and how reversible is it? A flag service is easy to swap behind the OpenFeature standard; a mesh touches every pod and is expensive to remove, so it gets a longer evaluation and a smaller first rollout.

And does the team have the capacity to run the bought thing well? Istio adopted by a team of two with no Kubernetes depth is worse than a good client library.

The trade-off I state explicitly: buying means accepting the tool's opinions and its upgrade cadence; building means owning every edge case forever. A managed offering — a cloud's mesh, a hosted Temporal, a hosted registry — is often the right middle, paying money to avoid on-call.

What I would not do is build any of these because "our needs are special"; in a decade the needs turned out special perhaps once.

Land it Buy commodities, price ownership rather than construction, and reserve building for the thing the company actually sells.

Likely follow-ups
"Give me a concrete total-cost-of-ownership comparison for a workflow engine."

Take a home-built saga orchestrator versus self-hosted Temporal versus Temporal Cloud, for a platform with a few hundred thousand workflows a day.

Build: four to six engineer-weeks to write the state machine, persistence, timers, and retries; then an ongoing quarter of an engineer's time forever for bugs, features the teams ask for — versioning of running workflows is the one everyone underestimates — and the risk that the author leaves.

Self-hosted Temporal: two weeks to stand up, a database it depends on, upgrades every few months, and on-call for one more stateful system — perhaps a fifth of an engineer ongoing plus infrastructure.

Temporal Cloud: a week to integrate, a monthly bill scaling with actions, and zero on-call for the engine.

Over three years the build costs the most in engineer time and delivers the least; self-hosting is cheapest in cash and moderate in time; the cloud is highest in cash and lowest in time.

Which wins depends on whether the company is short of engineers or of money, and that is the question I ask first.

"How do you evaluate a mesh before committing, given it touches every pod?"

With a bounded pilot that measures the things that will hurt. One namespace, three services with real traffic, for a month.

The measurements: the latency added per hop at p50 and p99 with the mesh's own metrics and the application's, as in the mTLS incident; the CPU and memory cost per pod for the sidecar or per node for ambient; the upgrade experience — I do at least one minor version upgrade during the pilot, because that is the ongoing cost; the pod-start behaviour under scale, as in the sidecar race; and how the team debugs a request through the proxies, because that is the daily cost.

I also list what we would use in year one — mTLS, retries, traffic splitting for canaries — and check that a smaller tool does not cover it; sometimes a gateway plus a client library does.

The exit criterion is written before the pilot: "adopt if p99 overhead under 5 milliseconds, sidecar CPU under 10% of the pod, and an upgrade completed without an incident". A pilot without an exit criterion becomes an adoption by momentum.

"When has building actually been right in your experience?"

When the piece encodes something specific to how the company makes money and no product is shaped for it.

The example I would give is a pricing rules engine for a business whose differentiation is complex, fast-changing pricing — a generic rules product either could not express the rules or could not evaluate them at the required rate, and the engine is the product's core.

Another is a thin internal abstraction over a bought tool — the messaging library in the RabbitMQ-to-Kafka migration — which is not building a broker but building the seam that makes the broker replaceable, and that is always worth it.

What does not qualify is "our scale is unusual"; the mature tools have seen larger. The test is whether the company's customers would notice the difference if the built thing were replaced by a bought one.

For a mesh, a registry, or a flag service, they would not.

"The team has already built a home-grown version of one of these. What do you do with it?"

I look at what it would cost to keep versus to replace, without sentiment.

If it is small and working — a thousand lines of feature-flag code with a database table — the honest answer might be to keep it behind the OpenFeature interface so it can be swapped later, and move on.

If it is large and unowned — a saga orchestrator its author left behind, with versioning problems the teams work around — replacement is the cheaper path, done as a migration: new workflows on the bought engine, old ones drained under the home-grown one, exactly like the saga migration in this drill.

What I do not do is a rewrite for purity or a public verdict on the people who built it; they solved a real problem when there was no better option.

I put the replacement on the platform roadmap with a date and a reason in cost terms, and the reason is usually "nobody wants to be on call for this".

Q144 · Design. "Design scheduled jobs for a service platform — nightly reconciliations, hourly reports — so that each job runs exactly once even with many instances of each service, and a missed run is noticed."

Reveal answer

Strong answer Requirements: a job scheduled for 02:00 runs once across all instances of the owning service, not once per pod; a job that fails is retried and then escalated; a job that silently does not run is detected; jobs are idempotent so a duplicate run is harmless.

Design: scheduling is done by the platform, not inside the pods — a Kubernetes CronJob per job that starts a single pod of the owning service in job mode, which sidesteps the "which of my 12 instances runs this?" problem entirely.

Where the job must run inside the long-lived service, a database lock decides: ShedLock or a similar library takes a row-level lease in the service's own database with a lease duration longer than the job's maximum runtime, so exactly one instance runs it and a crashed instance's lease expires — this is a lease, and the Distributed Systems primer explains why the lease must have a bounded duration and the holder must check it.

Every job is idempotent by design: it processes "everything since the last watermark" and records the watermark in the same transaction as its work, so a re-run repeats nothing.

Observability: each run writes a start and end row with status to a job_runs table; a metric of "seconds since last successful run" per job feeds an alert with a threshold just above the schedule interval, which is the only way a job that never started is noticed.

Failures: bounded retries with backoff inside the run, then an alert and a manual re-run endpoint. Trade-offs: CronJobs spread scheduling across many manifests; a small registry of jobs with owners keeps it visible.

What I would not do is @Scheduled on a multi-instance service with no lock — the job runs twelve times and nobody notices until the reconciliation sends twelve emails.

Land it Let the platform start one pod, or take a bounded lease in the database; make every job idempotent on a watermark; and alert on the job that did not run, because that one never raises its own hand.

Likely follow-ups
"Show me the ShedLock configuration and explain lockAtMostFor versus lockAtLeastFor."

The scheduled method is annotated @SchedulerLock(name = "nightlyReconciliation", lockAtMostFor = "PT2H", lockAtLeastFor = "PT5M"), with a LockProvider bean — JdbcTemplateLockProvider — pointing at a shedlock table with columns name, lock_until, locked_at, locked_by.

When the schedule fires on twelve instances, each tries to update the row to claim it, and only one succeeds.

lockAtMostFor is the lease duration: if the holder crashes, the lock is released after two hours, so it must be longer than the job's longest legitimate run or a slow run will be joined by a second instance — which is why the job is idempotent regardless.

lockAtLeastFor keeps the lock for at least five minutes even if the job finishes in seconds, which stops a second instance whose clock is slightly ahead from running the job again a few seconds later — the clock-skew lesson applied to scheduling.

ShedLock does not extend the lease during the run, so a job that exceeds lockAtMostFor is the case to design for.

"How does the watermark make the job idempotent, and what does the transaction look like?"

The job stores where it got to, and processes only what is after that point, in the same transaction as the work. The reconciliation job has a job_watermark row: last processed event timestamp or id.

Each run does, in one transaction: read the watermark, select the records after it up to a batch limit, process them and write their results, update the watermark to the last processed id, commit.

If the job crashes before commit, nothing moved and the next run repeats the batch — no duplicate work is visible because none was committed.

If two instances somehow run at once, the second's update of the watermark either finds it already advanced and processes nothing new, or conflicts on the row lock and waits.

The one subtlety is the outbox-style visibility gap: a record with a lower id that commits after the watermark passed it would be skipped, so the watermark uses a timestamp with a lag — process up to now minus one minute — or the records carry a processed flag instead of relying on the id order.

"Why not just use Kubernetes CronJobs for everything?"

For most jobs I would, and it is the first recommendation.

The cases where the in-process lease is better: a job that needs the service's warm state — caches, connection pools, a loaded rules set — and would take minutes to start cold; a job that runs every few seconds, where a pod per run is wasteful; and a job that must coordinate with the service's own request handling, such as the outbox poller.

CronJobs also have their own sharp edges: concurrencyPolicy: Forbid is needed or a slow run overlaps the next; startingDeadlineSeconds decides whether a missed schedule during a controller outage is run late or skipped; and a CronJob that fails silently is the same "did not run" problem, so the job-runs table and the seconds-since-success alert apply to both.

And there is the operational sprawl of many CronJob manifests, which the job registry addresses. The decision per job is written in the registry with its owner.

"The alert fired: the nightly job has not succeeded in 26 hours. What is the triage?"

The job-runs table first: is there a row for last night at all? No row means the job never started — the CronJob controller, the schedule, a suspended CronJob, or, for the in-process kind, no instance had the schedule enabled after a configuration change.

A row with status RUNNING and no end means it is stuck or the pod died — check whether the pod exists and its logs; with ShedLock, the lease may still be held, and the next run will wait until lockAtMostFor expires.

A row with status FAILED means it ran and broke — the error is in the row, and the retry budget was exhausted.

For each, the action differs: fix the schedule, kill and rerun, or fix the bug and rerun through the manual endpoint, which is why that endpoint exists.

Because the job is idempotent on its watermark, a rerun is safe at any time, and a rerun today processes both yesterday's and today's backlog. The alert threshold of 26 hours for a daily job is the schedule interval plus the longest expected run plus margin.

Q145 · Scenario. "In a design review, a team proposes three new services — catalogue, pricing, promotions — sharing one 'commerce' database for simplicity, with a plan to split it later. What do you say?"

Reveal answer

Strong answer I would first ask what problem the three services solve that one service would not.

If the honest answer is that one team owns all three and they will always deploy together, the better proposal is one service — or a modular monolith with three modules — and the shared database stops being a question.

If they are genuinely three teams' capabilities, then "share now, split later" is the trap to name: the shared database is a hidden, unversioned contract, and "later" is when the tables have foreign keys across the three, the pricing team's query depends on the catalogue team's index, and splitting means a data migration under load that nobody will schedule.

The evidence I would ask for: the proposed tables and which service writes each; the queries that cross the boundaries.

The compromise I would accept: one database server for cost, three schemas with three database users, each service granted access only to its own schema, and cross-schema JOINs forbidden by permission rather than convention — with events for the data that crosses.

That keeps the ownership rule, costs almost nothing extra today, and makes the later physical split a matter of moving a schema rather than untangling one.

What I would say plainly: the simplicity is real for the first month and imaginary after that, and the review's job is to protect the year.

Land it Either it is one service and the question disappears, or it is three and the schemas are separated by permissions today — "share now, split later" is a plan to never split.

Likely follow-ups
"Show me the permission setup that forbids cross-schema access in PostgreSQL."

One database, three schemas, three roles. CREATE SCHEMA catalogue AUTHORIZATION catalogue_svc; and the same for pricing and promotions.

Each service's role gets USAGE and the table privileges on its own schema only, and REVOKE ALL ON SCHEMA public FROM PUBLIC so the default schema is not a shared back door. Each service connects as its own role with search_path set to its schema.

The migration tool for each service runs as that role, so a migration that creates a foreign key to another schema fails at apply time with a permission error, which is the enforcement.

For the case where one team genuinely needs a read of another's data, the answer is an event and a local copy, not a GRANT SELECT; and if a grant is given anyway as a temporary measure, it is recorded with an expiry.

A nightly query on information_schema.role_table_grants lists any cross-schema privileges, which keeps the exception list visible.

"The team says three services in one repository and one deployment is a monolith by another name. Are they right?"

They are right, and that is fine if it is deliberate.

A modular monolith — one deployable with three modules whose boundaries are enforced in code, by package visibility and an architecture test such as ArchUnit, and whose data is in three schemas — has most of the design benefits of three services with none of the network costs: one deploy, one database transaction where it is needed, in-process calls.

What it lacks is independent deployment and scaling per module, and those matter only if the modules have different teams or different load profiles. The question I ask the team is which of those two they have.

If it is one team and similar load, the modular monolith is the better proposal and I would say so in the review.

If they expect to split into three teams within the year, the three-schema database and the enforced module boundaries are exactly the preparation that makes the later split a deployment change rather than a data migration.

"A year later they want to split the pricing schema into its own instance. What is the procedure?"

Because the schema is already isolated by permission, it is a data move with no untangling.

Set up the new instance, and use logical replication — a PUBLICATION for the pricing schema's tables on the old instance and a SUBSCRIPTION on the new — to copy and then stream changes, so the new instance stays current.

When lag is near zero, do a short cutover: pause the pricing service's writes for a few seconds — a flag that makes its write endpoints return 503 with Retry-After — wait for replication to drain, switch the pricing service's connection string to the new instance, resume writes, and drop the subscription.

Total customer-visible pause under a minute; and the reverse is the same procedure backwards if something is wrong. Then drop the old schema after a week.

Compare that with the shared-tables version: months of finding every query that joined across the boundary, and a cutover that cannot be reversed.

"What would you accept if they refuse the three-schema compromise?"

Then I go back to the first question — is this one service or three — and push for one, because three services on one set of shared tables is the worst of both: network hops with a hidden shared contract.

If they still want three services and shared tables, I would ask for the evidence in writing: which tables each writes, and the cross-boundary queries, and I would record in the review that the design has a known cost that the team has accepted, with the trigger for revisiting it — the first time a schema change in one service breaks another.

That is not a veto; a design review's job is to make costs visible and to make sure the decision is made by someone who will pay them.

What I would not accept silently is the word "later", because the review is the only moment when the split costs nothing.

Q146 · Design. "Design outbound webhooks for partners: they register a URL, we deliver events to it. Cover signing, retries, ordering, partner outages, and a partner who is slow."

Reveal answer

Strong answer Requirements: partners can verify a delivery came from us and was not altered; a partner outage of hours loses nothing; a slow partner cannot slow other partners; partners can recover missed events; we never spin forever on a dead URL. Design: events for webhooks are consumed from the platform's topics by a webhook dispatcher that writes one delivery row per event per subscription (QUEUED) and processes them from a per-subscription queue.

Each request carries a timestamp and an HMAC signature over the body with a per-subscription secret, so the partner verifies authenticity and rejects replays older than five minutes; secrets are rotatable with a two-key overlap.

Retries: exponential backoff with jitter over about 24 hours (1 minute, 5, 30, 2 hours, 6, 12), then the delivery is marked FAILED and the subscription is paused with a notification to the partner after a threshold of consecutive failures — no infinite retries.

Ordering: best-effort per subscription with a sequence number in each payload, and the documented rule that partners must tolerate out-of-order and duplicate deliveries, since retries make both inevitable; each event carries a unique id for their dedup.

Isolation: a bounded concurrency per subscription and a 10-second timeout per delivery, so a slow partner consumes only its own budget. Recovery: a replay API where a partner requests redelivery of events in a time range.

Observability: per-partner success rate and latency, visible to them in a dashboard, which halves the support load. Trade-offs: per-subscription queues need a scheduler that scales with subscriptions.

What I would not do is call partner URLs from the request path of the event's producer, or promise strict ordering.

Land it Sign every delivery, retry with a ceiling, isolate each partner's budget, and give them replay — a webhook system is a queue per partner with honest guarantees written on the box.

Likely follow-ups
"Show me exactly what the partner verifies. What goes into the signature and why the timestamp?"

The request carries two headers: X-Webhook-Timestamp with the Unix time of the send, and X-Webhook-Signature with v1= followed by the hex HMAC-SHA256 of the string "timestamp dot raw body", computed with the subscription's secret.

The partner recomputes the HMAC over the exact bytes they received, not over a re-serialised JSON object, because re-serialising changes whitespace and key order and the signature stops matching.

They compare with a constant-time comparison, such as MessageDigest.isEqual in Java, so timing does not leak the signature. The timestamp is inside the signed string so it cannot be altered, and they reject anything older than five minutes.

Without it, an attacker who captured one valid delivery could replay it forever and it would verify every time. With two active secrets during rotation the header carries two signatures, v1=... v1=..., and the partner accepts if any matches, then removes the old secret after the overlap window.

"What if a partner insists on strict ordering? Their system cannot cope with an 'updated' arriving before 'created'."

I would first offer the cheaper fix: put a monotonically increasing sequence number per subscription in every payload, and ask them to buffer and reorder, or simply to ignore any event whose sequence is lower than the last one they applied, which handles the common case of a retried old event arriving late.

If that is not acceptable, I can provide strict ordering at a cost: for that subscription, the dispatcher sends one delivery at a time and does not advance until the current one succeeds, so a single failed delivery holds back everything behind it.

That means their outage becomes a growing queue rather than a set of independent retries, and the retry ceiling of 24 hours has to become "pause the subscription and alert" instead of "mark failed and continue", otherwise a failed head-of-line event silently drops everything after it.

I would put that partner on a separate dispatcher pool so a stalled ordered queue never consumes threads meant for the others, and I would charge for it, because it is a genuinely more expensive product.

"A big partner's endpoint has been down for six hours and they have 400,000 queued deliveries. When it comes back, what happens?"

What must not happen is 400,000 requests hitting a freshly recovered endpoint in one burst, because that knocks it over again and we get blamed. Two controls prevent that.

First, the per-subscription concurrency cap, say 10 in flight, bounds the rate to roughly 10 divided by their response time, so at 200 milliseconds that is 50 per second and the backlog drains in a little over two hours.

Second, a circuit breaker on the subscription: after a run of consecutive failures the dispatcher stops attempting deliveries and probes with one request per minute; only when the probe succeeds does it reopen, and I would ramp the concurrency from 1 to 10 over a few minutes rather than jumping.

The backlog itself lives in the delivery table, not in memory, so it survives our own restarts. And I would tell the partner in the dashboard: "paused, 400,000 pending, probing", so their on-call engineer knows what to expect when they fix their side.

"How does the dispatcher scale when you have 20,000 subscriptions? A queue per subscription sounds expensive."

The queue per subscription is logical, not physical. The delivery table is partitioned by subscription id and indexed on (subscription_id, status, next_attempt_at). A pool of dispatcher workers claims work with SELECT ... FOR UPDATE SKIP LOCKED, taking up to N rows for one subscription at a time, where N is that subscription's concurrency cap, so fairness comes from claiming per subscription rather than from separate queues.

Subscriptions with nothing pending cost nothing.

At 20,000 subscriptions the hot part is the polling query, and I would keep it cheap by only scanning rows with next_attempt_at <= now() and status QUEUED, and by moving the FAILED and DELIVERED rows to an archive table after seven days so the live table stays small.

If polling becomes the bottleneck, the next step is a Kafka topic keyed by subscription id feeding the workers, with the table kept as the source of truth for status and replay.

I would verify with a synthetic load of 50,000 deliveries per minute in staging before committing to either.

"What would you cut if you had two weeks to ship the first version?"

I would ship signing, retries with a ceiling, and the per-subscription concurrency cap, because those are the three that prevent a security incident, an infinite loop, and one partner hurting another.

I would cut the replay API and replace it with a manual runbook: an engineer can re-queue deliveries for a partner with a SQL update on the delivery table, and we expose the proper API when the third partner asks.

I would cut the partner-facing dashboard and send a daily email with success rate instead. I would cut secret rotation with overlap and ship single-secret with a documented manual rotation, since no partner rotates in the first month.

What I would not cut is the delivery table itself, because without a durable record there is no retry, no replay, and no way to answer "did you send it", which is the first support question every webhook system gets.

Q147 · Design. "Design the service template — the 'paved road' — every new service starts from. What is in it, and what is deliberately not?"

Reveal answer

Strong answer Requirements: a new service is production-ready on day one; the platform's rules are defaults, not documentation; teams can leave the road when they have a reason, visibly.

In the template:

  • Build: a Spring Boot 3.5+/4.x project with the platform's parent build (dependency versions, plugins, container image build).
  • Observability: structured JSON logging with trace ids; Micrometer tracing and metrics exporting to the collector; a generated dashboard and burn-rate alerts.
  • Probes: liveness, readiness, and startup probes wired to shallow checks (health checks).
  • Outbound calls: an HTTP client bean with timeouts set and Resilience4j configured with sane defaults for breaker, retry with jitter, and bulkhead, so a client cannot be created without them (timeout, circuit breaker, bulkhead).
  • Messaging: Kafka producer and consumer configuration with idempotence, the cooperative or new protocol, an error handler with dead-letter publishing, and a processed-events guard table migration; an outbox table migration and poller (outbox, idempotent consumer, dead-letter queue).
  • Security: a JWT resource-server configuration that denies by default.
  • Deployment: graceful shutdown settings and a preStop hook in the Helm chart; resource requests, a PodDisruptionBudget, and an HPA stub.
  • CI: unit, Testcontainers integration, and Pact verification stages, plus can-i-deploy as the deploy gate.
  • Documentation: a README that lists these guarantees.

Deliberately not in it: business logic, a domain model, an ORM choice imposed beyond what the platform supports, and any shared library containing domain code — the template is copied once, and services evolve independently.

A bot raises pull requests when the template's platform bits change.

Trade-offs: a template team to maintain it. What I would not do is a shared "platform-core" jar that every service depends on at runtime; it becomes the monolith in a new coat.

Picture it A generated service on day one, then one template fix travelling to 80 services as bot pull requests, compared with the shared-jar alternative.

The setup: every service repository records which template it came from, and CI reads an exemption file, so leaving the road is a recorded decision.

.template-version and .exemptions.yamlruns offline
# .template-version
template: paved-road-service
version: 1.3.0

# .exemptions.yaml  (read by the CI pipeline)
exemptions:
  - stage: pact-verify
    reason: "no consumers yet; revisit when shipping-service calls us"
    owner: order-team
    expires: 2026-12-01

Make the invisible visible: the template splits a service into platform-owned files the bot keeps current and team-owned files it never touches.

what a generated service containsruns offline
new service: shipping-service   (from paved-road 1.3.0)

platform-owned (bot keeps current)        team-owned (never touched)
-----------------------------------       --------------------------
build parent + image build                business logic
JSON logging + trace id                   domain model
Micrometer tracing and metrics            endpoints
shallow liveness/readiness/startup        own schema migrations
HTTP client: timeout+retry+breaker+bulkhead
Kafka config + DLT + guard table
outbox table + poller
JWT deny-by-default
Helm: preStop, PDB, HPA stub
CI: unit, Testcontainers, Pact, can-i-deploy

The trace: the same tracing bug fixed through a shared jar and through the template bot.

call traceruns offline
# ❌ TRAP: shared "platform-core" jar, tracing fix released as 2.0.1
09:00  platform-core 2.0.1 released
09:10  payment-service rebuilds for an incident hotfix and pulls 2.0.1   ✗ unrelated change ships mid-incident

# ✅ FIX: template 1.4.0 and a bot
09:00  template 1.4.0 tagged
09:05  bot diffs platform-owned files in 80 repos, opens 80 pull requests   ✓
09:10  payment-service leaves its pull request open until the incident ends   ✓ the team picks the moment

What you see: the adoption dashboard shows how far the fix has travelled and who is lagging.

adoption dashboardruns offline
# illustrative output
template fix v1.3.0 -> v1.4.0, 80 services
moment      PRs opened   PRs merged   on 1.4.0   still on 1.3.x
day 0           80            0           0           80
day 3           80           41          41           39
day 14          80           74          74            6   <- chase these (74/80 = 92.5%)

Why: a runtime dependency forces the change on everyone at their next build, while a copied template with a bot lets each team choose when to merge, and the dashboard shows who has not.

What is in, what is out: each item is judged by whether it must exist from the first request and whether it ships domain code.

Template decision table
ItemIn the template?Reason
Timeouts, breaker, bulkhead wrapperYesA client cannot be created without them
Outbox and guard table migrationsYes (removable)Deleting them is a visible choice in the diff
Build parent POM or Gradle platformYes (shared artifact is fine)Pins versions and plugins, ships no code that runs in the service
Domain model, business logicNoServices evolve independently
Runtime "platform-core" jarNoBecomes the monolith in a new coat

Land it The template makes the right thing the default — timeouts, tracing, idempotency, contracts, shutdown — and stays out of the domain, so a team gets the platform for free and keeps its independence.

Likely follow-ups
"You said no shared 'platform-core' jar. But then how do you fix a bug in the tracing configuration across 80 services without 80 pull requests?"

You do raise 80 pull requests, but a bot raises them, not a person, and that is the deliberate trade.

The template lives in a repository with a version tag, and each service records the template version it was generated from in a file such as .template-version.

When the template changes, a job diffs the platform-owned files, the build parent, the logging configuration, the Helm chart skeleton, and opens a pull request per service with the change applied, using a tool like Renovate or a custom job.

Teams merge on their own schedule, which is the point: a shared jar would force the fix on everyone at their next build, including a team mid-incident.

The one place a shared artifact is acceptable is the build parent, a Maven parent POM or Gradle platform, because it pins versions and plugins without shipping code that runs in the service.

I would verify adoption with a dashboard of template version by service, and chase the stragglers older than two versions.

"What does a team have to do to leave the paved road, say to use a different HTTP client or skip Pact?"

Leaving should be possible, visible, and slightly annoying. The mechanism is an ARCHITECTURE.md or an exemption file in the repository stating what was changed and why, plus a review by the platform team, which is advisory, not a veto.

The CI pipeline reads the exemption file, so a skipped Pact stage is a recorded decision and not a silent deletion.

For the HTTP client case I would ask what the new client is missing from the template's wrapper, because the wrapper exists to guarantee timeouts and breaker defaults; if they configure those themselves and prove it with a test, fine.

What the platform team then does is count exemptions: if ten teams have made the same exemption, the template is wrong and gets changed. That feedback loop is the difference between a paved road and a fence.

"How do you keep the template from rotting? In a year it will be three Spring Boot versions behind."

The template is itself a service with an owner, a pipeline, and a nightly build.

Every night it generates a sample service, builds it, runs its tests, deploys it to a scratch namespace, and checks that tracing, metrics, probes, and shutdown all work, so a broken template is discovered before a team is.

Dependency updates arrive via Renovate on the template repository and are merged after that nightly passes.

As of Aug 2026 the template tracks the current Spring Boot minor, and a new minor is adopted within a month of release, with the migration notes captured as the bot pull request that goes to every service.

I would give the template a small explicit budget, one engineer roughly half time, and measure it with two numbers: median template version lag across services, and time from template change to 80 percent adoption.

If either grows, the template is rotting, and that shows up on a dashboard rather than in a surprise.

"Why is the outbox table and poller in the template? Not every service publishes events."

Because the alternative is that the services which do publish will do it wrong the first time. The dual-write problem, saving a row and then publishing a message as two separate operations, is subtle enough that every team rediscovers it after an incident.

Putting the migration and the poller in the template means the correct pattern is one annotation away, and the poller costs nothing when the table is empty, one cheap query per second.

A service that truly never publishes can delete the migration, and that deletion is a visible choice in the diff. The same reasoning applies to the processed-events guard table for idempotent consumption.

I would rather a team remove an unused safety mechanism than add a missing one under pressure. That said, I would keep it minimal: one table, one poller bean, and a documented property to disable it, not a framework.

"What would you cut from this template under time pressure?"

I would cut the generated dashboard and burn-rate alerts, because a service can go live with the platform's default dashboards and add its own later.

I would cut the Pact stage and the can-i-deploy gate, because contract tests need a consumer to be useful and the first services have none. I would cut the HPA stub and ship a fixed replica count.

What I would not cut, in order: the outbound client with timeouts and breaker, because a missing timeout is the most common cause of a cascading failure; the graceful shutdown settings and preStop hook, because without them every deploy drops requests; the deny-by-default security configuration, because adding security later means finding every endpoint; and structured logging with trace ids, because retrofitting it means touching every log line.

The rule is that I cut what can be added incrementally and keep what has to be present from the first request.

Q148. "The CTO read that a well-known video team cut costs 90% by merging its microservices back into one process, and asks whether we should do the same. How do you answer?"

Reveal answer

Strong answer I would take the question seriously rather than defensively, because sometimes the answer is yes.

The published case was a video-monitoring pipeline moved from serverless functions and step functions into one process.

It saved money because its services were doing fine-grained, high-volume, chatty work: every frame passed between components over the network and through storage.

The cost was almost entirely data movement and orchestration overhead, with no team-independence benefit because one team owned the whole pipeline.

The lesson is that that particular boundary was wrong, not that boundaries are wrong. So my answer has three parts.

  1. Find our equivalents: services with one owner that always deploy together and talk constantly are candidates to merge, and I would measure the cross-service traffic and cost to size the prize.
  2. Keep the boundaries that earn their cost: where different teams ship independently, where scaling needs differ by an order of magnitude, where a failure must be isolated.
  3. Give the CTO numbers rather than an opinion: here are the four services that should be two, the estimated saving, and the two we should never merge and why. Merging is a migration like any other, done with the strangler mechanics in reverse.

The mistake to avoid is treating architecture as a fashion — splitting because it was 2018 and merging because it is 2026 — instead of as a set of boundaries each of which has to pay rent.

Picture it Which pairs of services in our order platform are worth merging, what the saving is under two billing models, and the merge rolled out behind a flag.

The setup: the merge keeps the same interface, so the network call and the in-process call can both exist while traffic shifts.

StockPort with a flagruns offline
public interface StockPort {
    Reservation reserve(String sku, int qty);
}

class HttpStockClient implements StockPort { /* HTTP call to inventory-service */ }
class LocalStockAdapter implements StockPort { /* direct call into the inventory module */ }

@Bean
StockPort stockPort(FeatureFlags flags, HttpStockClient http, LocalStockAdapter local) {
    // ✅ FIX: the flag picks the path, so rollback is a flag flip, not a deploy
    return flags.isOn("stock-in-process") ? local : http;
}

Make the invisible visible: the call graph with calls per second on each edge shows which boundary is chatty.

topology before and afterruns offline
before                                 after merging order + inventory
[order] --540/s--> [inventory]         [order | inventory modules]   (one process)
   |                                        |
   +--180/s--> [payment]   keep             +--180/s--> [payment]    keep
   +--40/s---> [shipping]  keep             +--40/s---> [shipping]   keep

What you see: three data sources side by side, with the thresholds from the answer applied.

merge candidate tableruns offline
# illustrative output   thresholds: 500 calls/s or fan-out above 3, co-deploy above 70%, same team
pair                  calls/s   fan-out   deployed together   same team   verdict
order -> inventory       540       3.2           78%             yes       merge  ✓
order -> payment         180       1.0           12%             no        keep   ✗
order -> shipping         40       1.0            9%             no        keep   ✗

The trace: arithmetic for the saving depends on the billing model, which is why the 90 percent does not transfer.

worked arithmeticruns offline
# illustrative, assumed price
serverless pipeline, billed per transition
  10 frames/s x 5 transitions per frame = 50 transitions/s
  50 x 86,400 s = 4,320,000 transitions/day
  at an assumed 25 USD per million = 108 USD/day per stream
  merged into one process: 0 billed transitions

container platform, billed per CPU-hour
  chatty service uses 10 vCPU, 20% is HTTP + serialisation + mesh overhead
  merge saves 0.2 x 10 = 2 vCPU  -> about 20% of that service, not 90%

The fix: shift traffic by percentage with the rollback path tested at every step.

merge rolloutruns offline
# illustrative output
step                    traffic on in-process path   p99     errors   rollback to 2 processes
1 module boundary + test            0%               n/a     n/a      ✓
2 flag on, canary                  10%               41 ms   0.02%    ✓
3                                  50%               38 ms   0.02%    ✓
4                                 100%               35 ms   0.02%    ✓ (kept for 2 weeks)

Land it Each boundary is a line item — merge the ones that only cost, keep the ones that buy independence, and bring the CTO a list with numbers rather than a position.

Likely follow-ups
"Give me the concrete measurement. How do you find the services that should be merged?"

I use three data sources.

From tracing, I build a call graph weighted by calls per second between each pair of services; pairs above a threshold, say 500 calls per second or where one service's requests fan out to the other more than three times per request, are chatty.

From the deployment history, I compute for each pair how often they were deployed within the same hour; above 70 percent means they are not independent. From the ownership records, I check whether the same team owns both.

A pair that is chatty, co-deployed, and single-owner is a merge candidate with almost no downside.

Then I size the prize: the network and serialisation cost is the CPU spent in the HTTP client and server layers plus the load balancer and mesh sidecar overhead, which a profile puts at 10 to 30 percent of the CPU for chatty services, and the operational cost is the per-service fixed overhead of pipelines, dashboards, and on-call.

I present that as a table with the top ten candidates and an estimated monthly saving for each.

"What are the risks of merging two services, and how do you do it without an outage?"

The risks are the ones the split originally solved, whether or not anyone remembers: a shared failure domain, a shared deploy, and the possibility that the two used different library versions or different database transaction boundaries. Mechanically, a merge is a strangler in reverse.

First, the two codebases become modules in one build with an enforced boundary, using an architecture test that fails the build on cross-module imports outside the published interface.

Second, the network call between them is replaced with an in-process call behind the same interface, switched by a feature flag, so both paths exist for a while. Third, the merged process is deployed alongside the two old ones and traffic shifts by percentage.

Fourth, the database side: if the two services owned separate schemas, they keep separate schemas inside one process; merging data is a separate, later decision.

What I would verify: p99 latency and error rate on the merged path, and that a rollback to two processes still works at every step for two weeks.

"What if the CTO says do it anyway, merge everything into one deployable to cut costs?"

Then I would ask what problem we are actually solving, because "one deployable" and "cut costs" are different goals with different answers.

If cost is the goal, I would show that the infrastructure bill for a service-based platform is usually dominated by a handful of services and by data transfer, not by the count, so merging the long tail of small services saves little.

If the goal is fewer things to operate, a modular monolith for the small single-team services is a fine answer, and I would do it.

The case I would push back on hard is merging services owned by different teams that ship at different rates, because that recreates the release train and the shared outage the split was bought to escape.

I would put both options in writing with the numbers, run the first two or three merges as an experiment with measured before-and-after, and let the results decide the rest.

A CTO who wants numbers gets numbers; one who wants a fashion gets a polite disagreement with data attached.

"How much of the 90 percent saving in that case was really about architecture, and how much about the serverless pricing model?"

Most of it was pricing, and that matters for whether the lesson transfers.

The pipeline was paying per function invocation, per state-machine transition, and per object write to intermediate storage, and it was doing that for every video frame, so the bill was proportional to the number of hops multiplied by a very high event rate.

Moving into one process turned millions of billed transitions into function calls that cost nothing.

A platform running on ordinary containers or virtual machines is billed for CPU and memory hours, not per hop, so the same merge would save only the serialisation and network overhead, typically 10 to 30 percent of that service's CPU, not 90 percent of anything.

That is why I would measure our own hop cost rather than borrow their number. The architectural lesson does transfer: a boundary crossed thousands of times per second by one team's code is a boundary in the wrong place, whatever the billing model.

Q149 · Scenario. "You join as a lead. The platform has 300 microservices, 40 engineers, a two-week release train, and three outages a month. What do you do in your first ninety days?"

Reveal answer

Strong answer The ratio — 300 services for 40 people — is the diagnosis: seven or eight services per engineer cannot be owned, so most are orphans, and the release train says they are not independent anyway.

Evidence in the first two weeks:

  • Dependency graph: built from the tracing data.
  • Ownership: per service, who last changed it and who is paged for it.
  • Delivery speed: deploy frequency and lead time per service.
  • Outages: the post-mortems, looking for the common conditions.

Then three moves.

  1. Stop the bleeding: the three outages a month almost always share two or three missing controls (timeouts, breakers, shallow health checks, a dead-letter topic), and a template-driven pass to add those across the busiest fifty services is cheap and measurable.
  2. Consolidate: group services by owner and by "always change together", and merge the clusters into perhaps forty to sixty services, each with a team of five to eight. This is the biggest change and it takes the rest of the year, but the first mergers can be picked in month two.
  3. Make independence real for what remains: contract tests and can-i-deploy (consumer-driven contracts) so the release train can be dismantled service by service, and a platform team of three to five that owns the template, the pipeline, and observability.

What I would not do is a rewrite, or a freeze; both stall the business and the second one hides the problems.

At ninety days I would expect fewer outages, the first ten merges done, and one team off the train — and a written plan with numbers for the rest.

Picture it The week-two evidence, a chaos test showing a control that exists but does not work, the ninety-day scorecard at four moments, and a table for outages that survive the controls.

Make the invisible visible: the ratio and the ownership audit show what the numbers hide.

week-two auditruns offline
# illustrative output
services: 300   engineers: 40   ratio: 300 / 40 = 7.5 services per engineer
no change in 12 months and no pager owner:   96 services (orphans)
deployed on the two-week train:             271 of 300
last 6 post-mortems, root cause:
  missing or huge timeout ......... 3
  no breaker or bulkhead .......... 2
  deploy-induced .................. 1

The trace: why a control that exists can still do nothing.

breaker arithmeticruns offline
Resilience4j defaults: slidingWindowSize 100, minimumNumberOfCalls 100
low-traffic service: 0.2 calls/s
100 calls / 0.2 per s = 500 s of traffic before the breaker can open   ✗ outage is over by then
timeout 60 s: a hung call holds its thread for 60 s, so the pool drains long before any breaker opens   ✗

What you see: the chaos test, injecting a 5-second delay into one dependency in staging, before and after.

chaos testruns offline
# illustrative output   inject 5 s delay into inventory, caller = order-service
config               timeout   breaker   at t = 30 s
default as shipped   60 s      silent    caller threads 200/200 busy, p99 60 s    ✗
tuned and verified   800 ms    OPEN      fast failures, threads 14/200, p99 0.8 s ✓

What you see now: the scorecard, with targets written in week two so they cannot move.

ninety-day scorecardruns offline
# illustrative output
metric                              day 0   day 30   day 60   day 90
outages per month (same criteria)     3       3        2      at most 1
busiest 50 with chaos-verified controls  0   20       50        50
merges done and in production         0       0        3        10
teams deploying off the train         0       0        0        1

Why: if outages still do not fall, the post-mortems point at a different kind of cause, and each kind has its own fix.

Second-order causes
SymptomRoot causeAction
Many services fail at once, per-service breakers quietOne shared database or Kafka cluster overloadedCapacity and isolation of the shared system; bulkheads around it
Outages cluster right after release-train daysThe train is the triggerContract tests, can-i-deploy, smaller batches
Slow degradation at peak, no errors firstFleet under-provisioned, no autoscalingCapacity work and autoscaling

Land it Add the missing controls first, merge what one team cannot own, and dismantle the train one contract at a time — the goal is fewer, owned, independently deployable services, not fewer outages by luck.

Likely follow-ups
"You added timeouts and breakers to fifty services and the outage rate did not drop. What next?"

First I would check whether the controls are actually active, because a breaker with the default thresholds on a low-traffic service never opens, and a timeout set at 60 seconds is a timeout in name only.

The verification is a chaos test: inject a 5-second delay into one dependency in staging and confirm the caller fails fast at its configured timeout and the breaker opens.

If the controls are real and outages continue, the post-mortems are telling me the outages are of a different kind, and I re-read them for the pattern I missed.

Common second-order causes: shared infrastructure such as one overloaded database or one Kafka cluster that many services hit, where per-service breakers cannot help; deploy-induced outages, where the release train itself is the trigger and the fix is contract tests and smaller batches; or capacity, where the fleet is simply under-provisioned and autoscaling is absent.

Each of those has a different fix, and the point of the first ninety days is to have the data that tells me which one it is.

"How do you pick which services to merge first, and how do you avoid the mergers becoming a year-long distraction?"

I pick the first merges by lowest risk and highest signal: two or three services that one team already owns, that deploy together, that call each other constantly, and that have no other consumers.

Those are practically one service already, and merging them proves the mechanics, the build, the module boundary test, the flag-switched in-process call, in a month with almost no chance of an outage. The signal is the before-and-after: fewer pipelines, lower latency, one fewer thing on call.

To stop it becoming a distraction, I set a rule that merges are done by the owning team as part of normal work, budgeted at about 20 percent of their capacity, not by a central team, and that no merge starts without a written target of what the merged service is and a two-week rollback window.

I would track the count of services on a dashboard and expect it to fall by roughly ten a month; if it stalls, I would rather stop and understand why than push.

"Forty engineers is not many. Where do the three to five people for the platform team come from?"

They come from the fact that the current setup is already consuming more than five people's worth of effort, just spread invisibly across forty.

Every team is maintaining its own pipeline, its own dashboards, and its own version of the timeout configuration, and the release train has a coordinator role that is a job in itself.

So I would find the two or three engineers who are already the de facto platform people, the ones others go to when the pipeline breaks, and make it official, then add one or two as the mergers free up capacity.

The trade is explicit: for the first quarter, feature velocity drops by roughly ten percent.

I would put that number in front of the business with the outage cost next to it; three outages a month at even a modest revenue impact usually dwarfs ten percent of a quarter's features.

And I would make the platform team's success metric something teams feel: time from template to first production deploy, and outages per month.

"What would you do differently if it were 300 services and 300 engineers?"

Then the ratio is one service per engineer, which is a reasonable ownership density, and the diagnosis changes: the problem is not orphaned services but the release train and the missing controls. I would not consolidate aggressively; I would keep the boundaries and fix independence.

The order becomes: template-driven controls first, exactly as before; then contract tests and can-i-deploy to dismantle the train, which is the main lever; then a real platform team, which at that size is ten to fifteen people, owning the pipeline, observability, and the service catalogue.

I would still look for merge candidates, because 300 services always contain some that should be one, but as normal hygiene rather than the headline.

The other thing that changes at 300 engineers is that I cannot know every service, so the service catalogue with owner, on-call, and dependency graph becomes a first-month deliverable rather than a nice-to-have.

"How do you know at ninety days whether it worked?"

I would have written the targets in week two so nobody, including me, can move them afterwards. Outages: from three a month to at most one, measured by the same incident criteria used before I arrived, because changing the definition is how leads cheat.

Controls: the busiest fifty services with verified timeouts, breakers, and shallow health checks, verified by the chaos test rather than by code review. Consolidation: the first ten merges done and in production with no incident attributed to them.

Independence: at least one team deploying off the train on its own cadence, with contract tests as its gate, which proves the mechanism for everyone else.

And the plan: a written document with the service count target, the timeline, and the platform team's charter, agreed by the engineering managers.

If outages did not fall I would say so plainly and show what the data now tells me, because the ninety-day mark is where the guessing stops and the measured plan starts.

Q150 · Design. "Migrate the platform's event backbone from RabbitMQ to Kafka — 60 producers, 120 consumers — without losing or duplicating a message and without a big-bang cutover."

Reveal answer

Strong answer Requirements: every message reaches every consumer exactly once in effect; no coordinated deploy; each team moves on its own schedule; the old broker can be turned off with confidence. Design: the migration is a strangler over the broker.

  1. Insulate: every producer and consumer already goes through a thin messaging library or is made to, so the transport is one place per service.
  2. Bridge: a bridge service consumes each RabbitMQ exchange and republishes to the matching Kafka topic, carrying the RabbitMQ message id as a header (used as the Kafka message key's companion for dedup). Because the bridge is at-least-once, every consumer is made idempotent by message id before it moves, using a guard table. This is the step that makes "no duplicates" true.
  3. Move consumers first: a consumer switches from the RabbitMQ queue to the Kafka topic by flag and reads the same messages via the bridge, and its guard table absorbs any overlap during the switch. Consumers move one at a time, each watched for lag and error rate.
  4. Move producers: once every consumer of an exchange reads from Kafka, its producers switch to publishing to Kafka directly through the outbox, and the bridge for that exchange stops. The guard tables absorb the overlap again.
  5. Decommission: when no exchange has traffic for a week, the old broker is turned off.

Semantics to re-check per topic:

  • Ordering by key: RabbitMQ queues are ordered; Kafka orders per partition, so keys must be chosen.
  • Retention: a queue empties on acknowledgement, a topic keeps messages for its retention period.
  • Dead-letter handling: moves from RabbitMQ's dead-letter exchanges to a dead-letter topic with an error handler.

Trade-offs: months of dual running and idempotency work in 120 consumers. What I would not do is a weekend switch.

I would also not move producers before consumers, because that strands messages in the broker nobody reads.

Picture it The same message crossing the bridge twice, what the guard table does with it, and the state of the migration at four moments.

The setup: the guard table and the effect commit in one transaction, so a duplicate id rolls the whole thing back (idempotent consumer).

guard tableruns offline
CREATE TABLE processed_messages (
  message_id   VARCHAR(64) PRIMARY KEY,
  processed_at TIMESTAMP   NOT NULL
);

-- one transaction per message:
INSERT INTO processed_messages (message_id, processed_at) VALUES ('m-1001', now());
UPDATE inventory SET available = available - 1 WHERE sku = 'SKU-7';
-- a duplicate id violates the primary key: the transaction rolls back, the effect happens once

Make the invisible visible: the bridge crashes after publishing but before acknowledging, so RabbitMQ delivers the message again.

message timelineruns offline
# illustrative output
step  where       event                                              guard table        stock
1     RabbitMQ    deliver m-1001 to bridge                            -                  10
2     bridge      publish to orders.events offset 41, header m-1001   -                  10
3     bridge      crash before ack                                    -                  10
4     RabbitMQ    redeliver m-1001 (ack never came)                   -                  10
5     bridge      publish again, offset 42, header m-1001             -                  10
6     consumer    offset 41: insert m-1001 ok, stock -1               m-1001             9   ✓
7     consumer    offset 42: insert m-1001 fails, rolled back, skip   m-1001             9   ✓

What you see: the failure case, where the bridge did not copy the id into a header.

duplicate with no idruns offline
# illustrative output
offset 41  header message-id=(missing)  consumer extracted id = null  -> treated as new   stock 9
offset 42  header message-id=(missing)  consumer extracted id = null  -> treated as new   stock 8  ✗ double effect

The fix: copy the id into the Kafka header under the name the consumer reads, and add a consumer test that delivers the same message twice and asserts one effect.

What you see now: the migration at four moments, with the guard tables active before any consumer moves.

migration stateruns offline
# illustrative output
moment            producers publish to        consumers read from        bridge                   guard tables
start             RabbitMQ (60)               RabbitMQ (120)             off                      being added
phase 3, midway   RabbitMQ (60)               RabbitMQ 70 / Kafka 50     on, copies all exchanges  active on 120
phase 4, midway   RabbitMQ 20 / Kafka 40      Kafka (120)                on for exchanges still fed by RabbitMQ   active
end               Kafka (60)                  Kafka (120)                off                      stay

Land it Make every consumer idempotent, bridge the brokers, move consumers then producers one at a time behind flags, and let the guard tables absorb every overlap — the migration is safe because duplicates were made harmless before they could happen.

Likely follow-ups
"What are the semantic differences between RabbitMQ and Kafka that will bite a consumer during this migration?"

Four that I would check per consumer.

First, delivery model: RabbitMQ pushes to a consumer and removes the message on acknowledgement, so a queue is empty once consumed; Kafka retains messages for the topic's retention period and the consumer tracks its own offset, so a consumer can re-read, and a new consumer group starting at earliest will replay history it may not expect.

Second, ordering: a RabbitMQ queue is ordered end to end; Kafka orders only within a partition, so any consumer that relied on global order needs a partition key that keeps related messages together, usually the aggregate id.

Third, competing consumers: RabbitMQ shares one queue among any number of consumers; Kafka caps parallelism at the partition count, so a topic with six partitions cannot be consumed by more than six instances.

Fourth, dead-lettering and per-message TTL: RabbitMQ does both natively; in Kafka the consumer's error handler must publish to a dead-letter topic itself, and there is no per-message expiry. Each of those is a line in the per-consumer migration checklist.

"A consumer moved to Kafka and started processing duplicates in bulk. The guard table did not stop it. Why not?"

The likely cause is that the guard table is keyed on something that changed across the bridge.

If the consumer's dedup key is the RabbitMQ message id but the bridge did not copy it into a Kafka header, or copied it under a different header name, every Kafka message looks new.

The second likely cause is that the guard check and the business write are not in the same transaction, so a crash between them leaves the effect applied but the id unrecorded, and the retry applies it again; that bug existed before but the switch produced enough redeliveries to expose it.

The third is a consumer group that started at earliest and replayed a week of history that predates the guard table's rows.

To diagnose, I would pull one duplicated message from both brokers and compare the id the consumer actually extracted, then check whether the guard insert and the effect share a transaction boundary in the code.

The fix is whichever is broken, and a consumer test that replays the same message twice and asserts one effect, which should have existed before the move.

id comparisonruns offline
# illustrative output
RabbitMQ  message_id = m-1001
Kafka     header message-id = (missing)   <- bridge dropped it, so every message looks new  ✗
guard insert and stock update: separate transactions  <- second suspect
"How do you verify at each step that no message was lost, not just that none was duplicated?"

Loss is harder to see than duplication because a lost message is silent. I would count at three points.

The bridge maintains per-exchange counters of consumed and republished messages, exported as metrics, and the difference must be zero over any window longer than the bridge's own retry horizon.

Each consumer's guard table gives a count of distinct ids processed per hour, which I compare against the producer's outbox count for the same hour; they must match within the in-flight lag.

For the switch itself, I run the moving consumer on both transports for a bounded window, an hour say, with the Kafka side in shadow mode that records ids but applies no effect, and diff the two id sets before flipping.

That shadow diff is the proof for that consumer, and it costs one flag and one table.

three countsruns offline
# illustrative output
bridge   consumed 1,204,311   republished 1,204,311   diff 0   ✓
inventory guard table, 10:00-11:00: 18,402 ids   order outbox, same hour: 18,405   in-flight 3   ✓
canary m-canary-0231 published 10:59   seen on topic 10:59   (alert after 3 misses)

Finally, a synthetic canary message with a known id is published every minute on every exchange and expected on the matching topic, alerting after three misses. Losing the canary means losing real messages.

"What if the requirement changed and a big-bang cutover over one weekend were the only option, say the RabbitMQ licence expires?"

Then I would keep the parts of the plan that make a cutover survivable and compress the timeline. Idempotent consumers still come first, because they are what makes the cutover's inevitable overlap harmless; that work is the bulk of the effort and cannot be skipped.

The bridge still runs, but only for a few days, to move any messages that land in RabbitMQ after producers begin switching.

The weekend itself becomes: freeze producers, drain every queue to empty and confirm with the management API, switch all consumers to Kafka behind their flags, switch producers, unfreeze.

The drain step is what replaces months of gradual movement, and it needs an explicit checkpoint where every queue reports zero and every consumer group reports zero lag.

I would rehearse the whole sequence in staging twice, with a rollback that switches the flags back and restarts the bridge in reverse, and I would keep the old broker running read-only for a week after.

The risk I would state plainly is that 120 consumers changing in one window means a defect in any of them is discovered by production, not by a canary.

"What would you cut under time pressure, and what is the one thing you would not?"

I would cut the thin messaging library abstraction in services that already have the transport isolated in one class, and accept a slightly larger per-service diff.

I would cut the per-topic re-check of retention and ordering into a default: seven-day retention and partition key equal to aggregate id, with exceptions found by asking each team one question.

I would cut the week of zero traffic before decommissioning to two days if the counters agree.

What I would not cut is making every consumer idempotent before it moves, because everything else in the plan assumes that duplicates are harmless; without it, the bridge's at-least-once delivery, the flag flips, and any retry become sources of double effects, and a double effect in a payment or an inventory consumer is an incident with a customer attached.

If a consumer genuinely cannot be made idempotent in time, it stays on RabbitMQ behind the bridge and moves last, and I would say which ones those are in the plan rather than hope.

Quick reference — Scaling and failure

cascading failure
One slow dependency fills every caller's threads, and the failure walks upstream. Timeouts and bulkheads are what stop it.
Load shedding
Rejecting work you cannot do, on purpose and early. A fast 503 beats a slow timeout for everyone.
Backpressure
Telling the producer to slow down, instead of buffering until you die.
thundering herd
Everything expires or retries at the same instant. Fixes: jittered expiry, request coalescing, stale-while-revalidate.
liveness vs readiness
Liveness failing means restart me. Readiness failing means stop sending me traffic. Getting these backwards restarts a healthy service under load.

11 · RecapWhat You Can Do Now

  • You can state the one real reason to split a system, price the costs honestly, and recommend a modular monolith when the numbers say so
  • You can draw a service boundary along a bounded context and explain why a boundary cut along a noun becomes the thing everyone is blocked on
  • You can make a network call survivable with the four tools — timeout, retry with jitter, breaker, bulkhead — and size each one from real numbers
  • You can explain why a timeout means "unknown" and design idempotency so that a retry can never charge a card twice
  • You can run a checkout across four services as a saga, order its steps around the pivot, and say what the customer sees in the middle
  • You can explain the dual-write problem with a crash sequence and close it with the outbox, CDC, and an idempotent consumer
  • You can follow one request across forty processes with a trace id, alert on burn rate instead of error counts, and keep the telemetry bill sane
  • You can ship a change through a canary with contracts verified, and diagnose a cascading failure by naming the feedback loop and where to cut it
🧠 Flex your memory

Close the page and write down, from memory: the two crash sequences that make the dual write lose or leak an event, and the exact set of things that must commit together in an idempotent consumer for at-least-once delivery to become exactly-once effect. Then reach back to Chapter E8's isolation chapter: why can an outbox poller that tracks a high-water mark on a sequence column skip a row under READ COMMITTED — and which two designs avoid the gap?

12 · SummaryAll 29 Patterns on One Page

Every architecture pattern in this chapter, each with the problem it solves and the solution in one line. Click a pattern name to jump to its full breakdown.

02 · Why and when to split

4 patterns.
PatternProblemSolution
Modular MonolithYou want clear team boundaries without the complexity of network calls between services.Keep one codebase, but divide it into strict, independent modules with clear rules.
Bounded ContextSharing one single "Customer" model tangles every team's changes together.Give each team its own separate definition and model for shared concepts.
Strangler FigRewriting a giant legacy app all at once takes too long and is too risky to launch.Replace the old system piece by piece until the new one takes over completely.
Anti-Corruption LayerA messy legacy system leaks its ugly data rules into your clean new code.Build a translator between the two systems to convert old data formats into clean ones.

03 · Communication

8 patterns.
PatternProblemSolution
TimeoutA frozen service can trap your app's workers forever if they wait without a limit.Set a strict stopwatch on every network call so your app stops waiting after a few seconds.
Retry with Backoff and JitterThousands of apps retrying at the exact same second will crash a recovering server.Wait progressively longer between retries, adding a random delay so retries spread out.
Circuit BreakerApps waste resources repeatedly calling a service that is already broken.Temporarily stop all calls to a failing service so it has time to heal.
BulkheadOne overloaded feature can eat up all server resources and crash the whole app.Isolate resources into separate pools so one failure does not sink the entire system.
Service DiscoveryCloud servers constantly start and stop, making hard-coded IP addresses useless.Use an automatic phonebook that tracks the live addresses of all running services.
API GatewayMobile and web apps should not have to track and authenticate against dozens of internal services.Put a single front door in front of your services to handle security and routing.
Backend for Frontend (BFF)One generic API sends too much data to mobile apps and too little to web apps.Build a custom mini-backend tailored specifically for each type of user screen.
Sidecar and Service MeshWriting security, retries, and logging code inside every single service wastes time.Attach a tiny helper program next to each service to handle all networking chores automatically.

04 · Data, sagas, outbox

8 patterns.
PatternProblemSolution
Database per ServiceShared database tables prevent teams from changing schemas or deploying independently.Give each microservice its own private database that no other service can touch directly.
Saga (Orchestration)A multi-service action fails halfway through, leaving data out of sync.Use a central manager to coordinate the steps and tell earlier services to undo work on failure.
Saga (Choreography)You need to coordinate a multi-service action without a central manager bottleneck.Have services react to each other's events, triggering the next step or undoing work on failure.
Transactional OutboxSaving to a database and sending a notification message can fail separately, causing lost updates.Save both the data and the outgoing message in the same local database transaction first.
Idempotent ConsumerNetworks sometimes deliver duplicate messages, which could charge a customer twice.Design services so processing the exact same message twice has the same effect as once.
Dead-Letter QueueOne corrupted message blocks the entire queue by failing over and over.Move broken messages to a separate quarantine folder after a few failed attempts.
CQRSA single data model cannot handle fast reads and complex writes equally well.Split your code and data models into separate paths for saving data and reading data.
Event SourcingOverwriting rows in a database erases the history of how the data changed over time.Save every single change as a permanent log of events, just like a bank statement.

05 · Operability and delivery

5 patterns.
PatternProblemSolution
Distributed TracingOne user request crosses dozens of services, making bugs impossible to find in separate logs.Attach a unique tracking ID to every request to follow its entire journey on one timeline.
Consumer-Driven ContractsUpdating an API accidentally breaks other apps that depend on it.Have API consumers write automated tests defining what data they expect before changes deploy.
Blue-Green DeploymentUpdating live software causes downtime and makes rolling back slow and risky.Run two identical environments, deploy to the idle one, and flip traffic over instantly.
Canary ReleaseA bad code update affects 100% of your users the second it launches.Release the update to just 1% of users first to catch errors safely before a full rollout.
Externalized ConfigurationHard-coding settings forces code rebuilds per environment and risks leaking passwords.Store settings and secrets outside the code and load them when the app starts.

06 · Scaling and failure

4 patterns.
PatternProblemSolution
Rate LimitingOne aggressive user or bot can hog server capacity and slow down everyone else.Cap the number of requests a single user can make per minute.
Load SheddingUnder heavy traffic, every request slows to a crawl until the whole system crashes.Reject low-priority traffic immediately when overloaded to keep the core app fast.
Cache-AsideRepeatedly reading the same data overloads your slow main database.Check fast temporary memory first, only querying the database when data is missing.
Health ChecksThe platform keeps sending users to a broken server instance that cannot respond.Regularly ping every server and automatically replace any instance that stops answering.