Skip to content
Tech Interview Prep
Technical interview guide

Integration Patterns

The standard ways two systems exchange data (sync API calls, async messaging, batch, and webhooks) and when each fits.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Azure Architecture Center and AWS Prescriptive Guidance integration patterns current 2026-08-31.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Choose synchronous or asynchronous integration for order submission.

Answer

Use synchronous integration for the acceptance boundary and asynchronous for fulfillment. The caller needs an immediate answer on whether the order was accepted: validation, inventory reservation, payment authorization, and a durable order ID. That path should be bounded and idempotent. Fulfillment (picking, packing, shipping, notifications) runs asynchronously with explicit status.

Assumptions: typical e-commerce order, caller is a web or mobile client, fulfillment takes minutes to days. If fulfillment is instant (digital goods), a single synchronous call is simpler. If the caller is a POS terminal that must know final state, keep it synchronous but budget a longer timeout.

Mechanism: The synchronous path does four things: validate payload, reserve inventory, authorize payment, and persist the order plus an outbox event in one transaction. The outbox event is the publication intent. A relay process polls the outbox and publishes to a queue (Kafka, SQS). The response is 202 Accepted with order ID and status ACCEPTED. The client polls a status endpoint or receives a webhook.

Why bounded? Because each dependency can fail or slow down. Set a total timeout of 2 seconds. Per-step p99 budgets:

stepp99 budgettimeout
validate payload5 ms50 ms
reserve inventory40 ms500 ms
authorize payment120 ms800 ms
insert order + outbox15 ms200 ms
total180 ms2 s

If any step exceeds its budget, return 503 with Retry-After: 1. The client retries with the same idempotency key.

Idempotency: client generates a UUID per order attempt. Store it in a unique index. Here is the PostgreSQL 15 pattern:

SQL
CREATE TABLE orders (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  idempotency_key TEXT UNIQUE NOT NULL,
  status TEXT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

INSERT INTO orders (idempotency_key, status)
VALUES ($1, 'ACCEPTED')
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id;

Trace: first call with key 'abc' inserts and returns id. Second call with same key: ON CONFLICT DO NOTHING returns no row; application then runs SELECT id FROM orders WHERE idempotency_key = 'abc' and returns the existing id. Duplicate submit is idempotent.

Async fulfillment: outbox relay polls every 100 ms. Publishes to Kafka topic orders.fulfillment with acks=all and enable.idempotence=true (both defaults in Kafka 3.0+). Consumer updates status to FULFILLING, then SHIPPED. Consumer lag alarm at 1000 messages. Dead-letter queue after 5 attempts. For SQS, set visibility timeout to 5x expected processing time (default 30 s, max 12 h).

Failure modes: client disconnect during sync call. Server may still process, so idempotency key prevents duplicate. Dependency loss: payment service down: sync path fails fast with 503; async path retries with exponential backoff. Delayed worker: consumer lag grows; detect via lag metric and alert. Duplicate submit: unique index returns same order ID.

When not to use: if the caller cannot handle eventual consistency (e.g., financial settlement), keep the whole flow synchronous with a longer timeout and compensating transactions. If fulfillment is trivial, skip the queue.

The response must be truthful: 202 means accepted, not completed. Give a correlation ID (the order ID) and a status URL.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Choose between a queue and an event stream.

Answer

Core answer

First question I'd ask: is each item a unit of work that exactly one worker should complete, or an immutable fact that several independent readers each need in order? That distinction decides it.

If it's work (send this email, charge this card, transcode this file) use a queue: SQS, RabbitMQ, or Pub/Sub in pull mode. The broker hands a message to one consumer, holds it invisible for a visibility timeout (SQS default 30 s, max 12 h), and deletes it on ack. Retention is a safety net, not the design: SQS keeps unacked messages 4 days by default, 14 max.

If it's a fact (order placed, sensor reading, click) use a log: Kafka, Kinesis, or Pub/Sub with a subscription per reader. Records are appended to a partition and retained regardless of who read them (Kafka default log.retention.hours=168, 7 days). Each consumer group tracks its own offset, so five teams read the same events at five positions, and any of them can rewind and reprocess.

Mechanism: why ordering and fan-out trade off

Kafka guarantees order only within a partition. Global order therefore requires one partition, which caps a consumer group at one active consumer: no parallelism. Want 12 consumers? Use 12 partitions and you get 12 independent orderings, not one. Partition count sets both max parallelism and the granularity of ordering. SQS FIFO makes the same trade with message group IDs: order within a group, and each group processes at 300 msg/s (up to 3,000 with batching), versus standard SQS which is effectively unlimited but only best-effort ordered.

DimensionQueue (SQS/RabbitMQ)Stream (Kafka/Kinesis)
Deliveryone consumer, delete on ackevery consumer group reads all
OrderingFIFO queue or message groupper partition only
Retention4 days default, 14 max (SQS)7 days default (Kafka), configurable
Replayno: gone after ackyes, reset offset
Parallelismadd consumers freely≤ partition count per group
Delete one recordnatural on ackrewrite segment / tombstone

Failure modes

Visibility timeout expiry: a worker runs longer than 30 s, SQS redelivers, the job executes twice. Detect with ApproximateNumberOfMessagesVisible flat while ApproximateNumberOfMessagesNotVisible climbs, plus duplicate side effects; fix with idempotency keys and a timeout above p99 processing time.

Retention outrunning the consumer: a Kafka group falls behind past 7 days and segments are deleted before it reads them. Silent data loss. Detect with consumer lag (kafka-consumer-groups --describe, the LAG column) trending toward the retention window; alert on lag in seconds, not lag in messages.

Rebalance storms: processing exceeds max.poll.interval.ms (default 300,000 ms), the consumer is evicted, the group rebalances, lag spikes, repeat. Detect in broker logs and a sawtooth lag curve.

What changes the decision

If a new consumer needs history, a queue can't give it: you'd dual-write to a log. If PII must be erasable, an append-only log fights you: you rewrite segments or lean on compaction tombstones, whereas a queue deletes on ack. Prototype the partition-key choice and the replay path before committing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design competing consumers for bursty image processing.

Answer

Assumptions I'd state before designing: images are 2–10 MB, each transform costs 0.5–3 s of CPU, arrival is bursty (baseline ~20/s, peaks ~500/s for a few minutes), images are independent so no ordering is required between them, and at-least-once delivery is acceptable provided outputs are idempotent. Completion SLO: p99 under 30 s from upload to output key existing.

Core answer. Keep bytes out of the queue. Upload to S3, then publish a claim-check message carrying {bucket, key, sha256, transform, tenant_id}. N identical workers compete on one SQS standard queue. Standard, not FIFO: images are independent, and a FIFO queue caps at 300 msg/s per queue without batching (3,000 with batches of 10) and serialises everything behind one slow message. The visibility timeout is the lease: set it above p99 processing time and extend it with ChangeMessageVisibility heartbeats, so a slow-but-alive worker doesn't get its message handed to someone else. After maxReceiveCount (3) the message lands in a DLQ.

OptionOrderingPer-message leaseBurst behaviourPick it when
SQS standardnoneyes, visibility timeoutscales with consumer countindependent jobs, at-least-once OK
Kafka consumer groupper partitionno, offset commit onlyparallelism capped by partitions; one slow record blocks its partitionyou need per-key order or replay
Postgres SELECT … FOR UPDATE SKIP LOCKEDnonetransaction-scopedDB becomes the bottleneck around a few thousand jobs/sthe job must be enqueued in the same transaction as a business write

Sizing. 500 images/s × 1.2 s CPU = 600 vCPU-seconds per second, so 150 workers at 4 vCPU each, or 600 single-vCPU workers. p99 render is 8 s, so visibility timeout 60 s with a heartbeat every 20 s. Scale on ApproximateAgeOfOldestMessage (target 20 s), not ApproximateNumberOfMessagesVisible: the latter drops the moment messages go in-flight, so it reads low exactly when you're behind.

Idempotency is the load-bearing part. The output key is derived from the input, and the write is conditional, so a redelivery is a no-op:

Python
# Python 3.12, boto3 1.35+ (S3 conditional writes, If-None-Match: *, GA Nov 2024)
def handle(msg):
    job = json.loads(msg["Body"])
    key = f"out/{job['sha256']}/{job['transform']}.jpg"
    try:
        s3.put_object(Bucket=OUT, Key=key, Body=render(job), IfNoneMatch="*")
    except ClientError as e:
        if e.response["Error"]["Code"] != "PreconditionFailed":
            raise          # 412 means another worker already produced it
    sqs.delete_message(QueueUrl=Q, ReceiptHandle=msg["ReceiptHandle"])

Trace of a duplicate: worker A renders, writes the key, then dies before delete_message. The lease expires, B receives the same message, renders again, put_object returns 412, B swallows it and deletes. One output, two renders, which is why render cost, not correctness, is what you pay for at-least-once.

Failure modes and how you see them. Poison input (truncated JPEG) fails three times and lands in the DLQ: alarm on DLQ depth, don't auto-retry it. Downstream throttling (a face-detection API at 50 rps) is handled by capping consumer concurrency below that limit; the queue absorbs the burst instead. A hot tenant backfilling 100k images starves interactive uploads, so give each tenant a queue or a fairness token. Regional recovery means the queue and bucket are in the same region and the DLQ is drained by a replay tool, not by hand.

When not to use this. If stage 2 needs stage 1's output for the same image in order, competing consumers on one queue gives you nothing: use Kafka with image_id as the partition key, or a Step Functions state machine. If the work is under ~10 ms, queue round-trip and visibility bookkeeping dominate; do it inline. And you never get exactly-once: the window between commit and delete guarantees at-least-once, so idempotency is not optional.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Preserve per-customer order while scaling consumers.

Answer

First I'd pin down the invariant. "Per-customer order" usually means one of three things: total order of every event for a customer, order per aggregate (order_id, invoice_id), or serialized updates to one account. The key follows from that. If it's total per customer, key by customer_id. If it's per order, key by order_id and you get far more parallelism. I'd state that assumption before choosing a mechanism.

With Kafka, a partition is an ordered log. A consumer group assigns each partition to exactly one consumer. If I produce with key=customer_id, the default partitioner hashes that key to a partition, so all of customer 7's records land in the same partition and are consumed in offset order by one consumer. Different customers spread across partitions and run concurrently. With 20 partitions, that topic supports at most 20 active consumers in the group; the 21st sits idle. If each customer peaks at 5k events/s and total is 200k events/s, 20 partitions can carry it only if no single customer exceeds one partition's capacity. A hot customer pins one partition; adding consumers does nothing.

I'd carry a version per aggregate and a unique event_id. The consumer keeps last_applied_version per key. On each record: if version <= last, reject as stale; if version == last+1, apply and advance; if version > last+1, you have a gap. Pause that key's processing: in a keyed stream processor like Flink, hold the key's state; in a plain Kafka consumer, buffer the record and continue other keys in the partition, or pause the partition if the invariant requires strict blocking. Repair from the authority (compacted topic, database, or replay from an earlier offset). A gap timeout, say 30 seconds in this example, triggers repair or DLQ for that key. Duplicates are normal with at-least-once: after a crash before offset commit, the batch replays. Dedupe on event_id with a unique constraint in the sink; detection is duplicate-key counter, cost is extra writes and storage.

Trace:

offsetkeyevent_idversionactionlast after
0cust-7e11apply1
1cust-7e22apply2
2cust-7e11reject stale2
3cust-7e44gap, pause cust-72
4cust-9e51apply1

Failure modes and detection: poison pill. Same offset crashes consumer repeatedly; after 3 retries route to DLQ and commit, but that skips order for that key, so only if the invariant allows. Rebalance: partition moves mid-batch; in-flight records replay, duplicate spike. Detection: rebalance listener plus duplicate counter. Hot key: one partition's lag grows while others idle; detection: per-partition lag and per-key backlog age, not total throughput. Per-key backlog age is max(now - event_time) for unprocessed records grouped by key; alert if p99 > 30s (hypothetical).

Alternatives: single partition gives global order but no scaling. Per-customer actor/queue (e.g., Redis Streams per customer) gives finer control but you own failover and millions of queues. Subpartitioning a customer by hash(customer_id, shard) breaks total order; it's safe only if operations commute or you merge with version vectors. If the invariant is per order, key by order_id and avoid the hot-customer problem entirely. If it's account balance, key by account_id. The deciding question is: what must never be reordered? That key is the partition key.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design an idempotent payment-command consumer.

Answer

Assumptions

  • Commands arrive at-least-once from a queue (Kafka, SQS): the same command can be delivered twice within seconds and again hours later on a retry.
  • The provider is Stripe-shaped: it accepts an idempotency key, replays the original response for a repeated key, and rejects the same key with a different body. Stripe retains those keys for 24 hours.
  • One Postgres primary owns the command table, so a unique constraint is a real serialization point.

Core answer

The client generates a UUIDv4 per user intent (122 bits of randomness) and sends it as client_key. I derive the storage key as sha256(payer_id || merchant_id || operation || client_key). Scoping to payer, merchant and operation means the same client_key from a different payer cannot collide, and it makes the key meaningful in an audit.

I also store a canonical fingerprint of the request body (sorted JSON, hashed). The key says which command; the fingerprint says what it asked for.

SQL
CREATE TABLE payment_command (
  idem_key     text PRIMARY KEY,
  fingerprint  text NOT NULL,
  state        text NOT NULL,  -- created | in_flight | succeeded | failed | pending
  provider_ref text,
  result       jsonb,
  updated_at   timestamptz NOT NULL DEFAULT now()
);

The insert is the serialization point:

Python
row = insert_or_select(idem_key, fingerprint)   # INSERT ... ON CONFLICT DO NOTHING, then SELECT
if row.fingerprint != fingerprint:
    raise Conflict("key reused with a different payload")   # 409, never overwrite
if row.state in ("succeeded", "failed"):
    return row.result            # replay the stored outcome, no provider call
if row.state == "in_flight":
    return Pending(row.idem_key) # another worker owns this command

Only the worker that won the insert moves created -> in_flight and calls the provider, passing the same idem_key as the provider idempotency key. That second key is what covers a crash after the provider charged but before we recorded it: the retry replays the provider's own response instead of charging again.

State transitions use compare-and-set so two workers can't both finalize:

SQL
UPDATE payment_command SET state='succeeded', result=$2, provider_ref=$3
WHERE idem_key=$1 AND state='in_flight';   -- 0 rows updated means someone else moved it

Trace: duplicate delivery

Two workers receive the same command. A wins the insert, sets in_flight, calls the provider. B's insert conflicts, reads in_flight, returns Pending. The provider charges once and returns ch_123. A CASes to succeeded. B's client retries, reads succeeded, gets the stored result. One charge, one row.

Failure modes

  • Crash between provider success and CAS. The row sits in in_flight. Detect it by age: any in_flight row older than the provider timeout (30s is a reasonable ceiling) is suspect. Recover by querying the provider with the idempotency key: inside its 24h window it returns the original result. Past 24h the key has expired, so reconcile against the provider ledger by provider_ref, not by replaying the key.
  • Forged or replayed callbacks. Verify the signature (Stripe sends Stripe-Signature, an HMAC over the raw body) and dedupe on the provider's event id, not on our idem_key: one command can produce several events.
  • Key reuse with a different payload. Return 409 and log it. Silently overwriting turns a client bug into a wrong charge.

Trade-offs

A Redis SETNX is faster than the insert, but eviction loses the record you need for reconciliation, so Redis can only be a front cache; the table stays the source of truth. For reversals I issue a compensating refund as a new command with its own key rather than deleting or mutating history: the ledger stays append-only and auditable, at the cost of two rows per reversal.

Retention follows the retry window, not the provider's: keep rows at least as long as the longest client retry plus the provider key window. If clients retry for 7 days, retain 7 days and archive after; deleting at 24h reopens the duplicate window for late retries.

This design assumes a single-writer store. In active-active multi-region, the unique constraint no longer serializes, and you need per-payer routing or a consensus store before the same guarantee holds.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Implement a transactional outbox for customer updates.

Answer

Core answer

Assume one service owns the customer aggregate in a relational DB (Postgres 14+), events go to a broker (Kafka), and consumers maintain projections. The problem is the dual write: committing the customer row and publishing the event are two systems, and a crash between them either loses the event or publishes one for a rolled-back change.

The outbox removes the dual write by making the event part of the same local transaction as the state change. One INSERT into outbox alongside the UPDATE on customers; both commit or neither does. A separate relay reads committed outbox rows and publishes them. Because the relay can crash after publishing but before recording progress, delivery is at-least-once, so consumers must deduplicate and enforce per-aggregate version.

Schema and claim

SQL
CREATE TABLE outbox (
  id           bigserial PRIMARY KEY,
  event_id     uuid        NOT NULL UNIQUE,
  aggregate_id uuid        NOT NULL,
  version      bigint      NOT NULL,
  type         text        NOT NULL,
  schema_ver   int         NOT NULL,
  payload      jsonb       NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now(),
  claimed_at   timestamptz,
  claimed_by   text,
  attempts     int         NOT NULL DEFAULT 0,
  published_at timestamptz,
  UNIQUE (aggregate_id, version)
);

The relay claims a batch with a lease, so a crashed relay's rows become claimable again once the lease expires:

SQL
UPDATE outbox SET
  claimed_at = now(), claimed_by = $1, attempts = attempts + 1
WHERE id IN (
  SELECT id FROM outbox
  WHERE published_at IS NULL
    AND (claimed_at IS NULL OR claimed_at < now() - interval '30 seconds')
  ORDER BY id
  LIMIT 100
  FOR UPDATE SKIP LOCKED
)
RETURNING id, event_id, aggregate_id, version, type, schema_ver, payload;

FOR UPDATE SKIP LOCKED (Postgres 9.5+) lets N relay instances claim disjoint batches without blocking each other. The relay publishes the batch, then sets published_at = now() for those ids. The claim transaction is short; the publish happens outside it.

Why consumer dedup is mandatory: a trace

Relay A claims rows 1–100, publishes 40 to Kafka, then the pod is killed. published_at is still null for all 100. Thirty seconds later the lease expires and relay B re-claims rows 1–100 and publishes all of them. Kafka now holds 40 duplicate events. Nothing in the relay prevents this without a distributed transaction across Kafka and Postgres, which is exactly what the outbox exists to avoid. So the consumer keeps a (consumer, event_id) dedup table and ignores repeats, and stores last_version per aggregate_id, rejecting any event with version <= last_version. That second check also repairs ordering: with multiple relays, per-aggregate order is not guaranteed even though the relay reads by id.

Trade-offs

  • CDC (Debezium tailing the Postgres WAL) skips the relay's write path and the outbox table, but ties you to a replication slot, needs the table's replica identity set, and is still at-least-once: you keep the consumer dedup either way.
  • A change table with a trigger is the same shape as an outbox with more DB overhead per write.
  • Direct dual-write (commit, then publish) has a window where a crash loses the event, or a publish succeeds for a transaction that later rolls back.
  • Outbox is the wrong tool when you need global ordering across aggregates (it only gives per-aggregate), when the DB write volume can't absorb the extra row per change, or when you already run CDC and don't want two delivery paths.

Failure modes and detection

failuresymptomdetection
relay down / laggingprojections stalemax(now() - created_at) WHERE published_at IS NULL over threshold
poison rowone row retried forever, blocks ordered batchesattempts > 5 AND published_at IS NULL
duplicate publishconsumer dedup hit rate spikesdedup-table inserts vs events consumed
out-of-orderversion regression at consumerconsumer rejects version <= last_version
restore to earlier pointold events republished, or rows lostcompare max(version) per aggregate in outbox vs downstream projection

Restore is the one that bites: a PITR restore rewinds the outbox to an earlier state, so the relay republishes events consumers already applied, and any events committed after the restore point are gone. Reconcile aggregate versions between the outbox and each projection after any restore, and treat a projection ahead of the outbox as a signal to replay rather than trust.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Use change-data capture as an integration source.

Answer

First 90 seconds

One PostgreSQL 15 primary is the system of record and only that service writes to it. Consumers are two downstream services and a warehouse. If they need business events, I put a transactional outbox in front of the log and replicate the outbox table; if they need row fidelity, I replicate the base tables. The contract I offer: at-least-once delivery, ordering guaranteed per primary key only, p99 end-to-end lag under 2 s, and a documented resnapshot path for when log retention is exceeded. Cross-table atomicity is an outbox decision, not something the connector gives you.

Setup that has to be right

  • Postgres: wal_level=logical (restart required; the default is replica), max_replication_slots default 10, max_slot_wal_keep_size default -1, i.e. unlimited, so one stalled consumer can fill the primary's disk. Cap it at 20GB.
  • REPLICA IDENTITY FULL only on tables whose consumers need the before-image of UPDATE and DELETE; the default carries the old primary key alone.
  • Debezium on Kafka Connect: plugin.name=pgoutput is the default, snapshot.mode=initial, heartbeat.interval.ms=10000 (default 0, off: with an idle database nothing advances the slot and WAL accumulates forever), offset.flush.interval.ms default 60000.
  • The checkpoint position is the Postgres LSN, or on MySQL the GTID plus binlog file and offset.
  • MySQL equivalent: binlog_format=ROW, binlog_row_image=FULL, GTID on, binlog_expire_logs_seconds default 2592000, i.e. 30 days.

Retention arithmetic

Held WAL is pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) read from pg_replication_slots. Assume a 2 MB/s write rate: a consumer down for one hour accumulates 7.2 GB. At max_slot_wal_keep_size=20GB that is about 2.7 hours of tolerance, so alert at 5 GB and page at 10 GB. wal_status='lost' means Postgres already discarded the changes: drop the slot and run an incremental snapshot driven by the Debezium signal table instead of pretending to replay.

Alternatives

SourceDeletes and historyCouplingCostChoose when
Poll an updated_at columnmisses hard deletes, latest state onlyread-only grant, no schema couplingrepeated index range scans; a 1M-row table at 0.5% churn is about 5,000 rows per polldelete rate under 0.1% and a 15-minute latency budget is fine
CDC on base tablesbefore-image only with REPLICA IDENTITY FULLwire format tracks the table schemano application change, extra WAL on the primaryfull row fidelity, sub-second
Transactional outbox plus CDCevent carries intent, including deletesone table the owning service controlsone extra insert per business transactionconsumers need domain events and storage renames must not leak

Failure modes

  • Duplicates: after a Connect crash, up to offset.flush.interval.ms, 60 s, of events replay. Detect by counting repeated (table, primary key, lsn) in the sink; dedupe in a keyed store with a 7-day TTL.
  • Unchanged TOASTed columns: Postgres logs a marker rather than the value, and Debezium emits __debezium_unavailable_value. Alarm on that placeholder and re-read the row by key.
  • Schema change: ADD COLUMN ... NOT NULL with no default becomes a required Avro field with no default, which is BACKWARD-incompatible and fails the task with IncompatibleSchemaException. Version the event and translate in the outbox.
  • Long transactions: logical decoding emits only at commit, so a 20-minute batch job stalls the whole stream; watch the transaction buffer metric.
  • Cross-table atomicity does not exist on per-table topics; enable the transaction metadata topic or use the outbox.

What changes the decision

No replication privilege, or a third-party SaaS source, kills CDC: use their webhooks or polling. Cross-table atomicity pushes you to the outbox. Deletes under 0.1% and a 15-minute budget make polling cheaper to operate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design the claim-check pattern for a message whose payload exceeds the broker's size limit: how do you store and reference the payload, and what happens when the object is missing or expired?

Answer

Treat the broker as a control plane, not a data plane. Write the payload to object storage, send a small message containing a claim check: object key, checksum, content type, size, and correlation ID. The consumer fetches the object, validates checksum and schema, then processes. If the object is missing, expired, or unreadable, the consumer dead-letters the message with the claim check and alerts; it never processes a dangling reference.

Mechanism. Producer: upload to a key like tenant/{tenant}/order/{orderId}/{uuid}. Use multipart upload and only send after the storage service confirms completion and returns an ETag/version ID. Then send the message. To avoid a message pointing at a missing object, write the blob first, then insert an outbox row in the same database transaction as the business change; the outbox relay sends the claim-check message. If the blob write succeeds and the DB fails, the blob is orphaned and cleaned by lifecycle policy. If the DB succeeds and the blob is missing, the consumer handles the dangling reference.

Token design. Do not embed long-lived credentials. Prefer the message carries only the object key and version; the consumer uses its own workload identity (IAM role, managed identity) to read. If you must use a pre-signed URL or SAS token, its TTL must exceed the maximum queue retention plus processing SLA, or the consumer must be able to re-sign. A 15-minute URL on a message that can sit in a queue for 4 days is a dangling reference waiting to happen.

Consumer validation. Fetch with conditional read (If-Match on ETag) to detect overwrite. Verify SHA-256 checksum, size, content type, and schema. Scan for malware if the payload is untrusted. Process idempotently using the message ID or correlation ID.

Missing/expired/unreadable. On 404, 403, checksum mismatch, or partial object: do not retry forever. Move to dead-letter with reason and claim check, emit a metric, and alert if the rate exceeds a threshold. A dangling reference is a data-integrity incident, not a transient error.

Access control and cleanup. Storage bucket/container private. Least-privilege read for consumers, write for producers. Lifecycle policy deletes objects after retention (e.g., 7 days) or after successful processing for single-consumer flows. For multiple consumers, keep until max retention or use reference counting. Never delete before all consumers have a chance to read.

When to prefer claim check over compression or chunking. Compression when the payload compresses well (JSON often 5-10x) and the compressed size fits the broker limit. Chunking when the broker supports large messages or you need streaming and order, but it adds reassembly state, partial-failure handling, and consumer complexity. Claim check when the payload is large binary, already in object storage, many consumers need it, or you want to keep broker memory and throughput predictable. Example: a 50 MB PDF invoice on a broker capped at 256 KB.

Artefacts.

Sequence: Producer -> Object store: PUT payload (multipart, checksum) Object store -> Producer: 200 + ETag Producer -> DB: outbox row with claim check Outbox relay -> Broker: message {key, etag, sha256, size, content-type} Consumer -> Broker: receive Consumer -> Object store: GET key If-Match etag Object store -> Consumer: bytes or 404/403 Consumer -> Broker: ack or dead-letter

Comparison table:

ApproachBest whenCost
Claim checkPayload > broker limit, binary, many consumersExtra storage, fetch latency, dangling refs
CompressionText compresses well, fits limitCPU, not for binary
ChunkingBroker supports large messages, streamingReassembly state, partial failure

Code (Python 3.12, boto3): python import hashlib, boto3 s3 = boto3.client("s3") def produce(bucket, key, payload): sha = hashlib.sha256(payload).hexdigest() s3.put_object(Bucket=bucket, Key=key, Body=payload, ChecksumSHA256=sha) return {"key": key, "sha256": sha, "size": len(payload)} def consume(msg): try: obj = s3.get_object(Bucket=bucket, Key=msg["key"], ChecksumMode="ENABLED") body = obj["Body"].read() if hashlib.sha256(body).hexdigest() != msg["sha256"]: raise ValueError("checksum mismatch") return body except s3.exceptions.NoSuchKey: dead_letter(msg, "claim check missing") except s3.exceptions.ClientError as e: dead_letter(msg, f"claim check unreadable: {e}")

Failure modes: orphaned blobs (lifecycle policy, inventory), dangling references (dead-letter, alert), expired access (identity-based read), partial upload (multipart complete atomic), cleanup race (retention > max processing), security leak (private bucket, least privilege).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design message routing for an order-placed event that must reach billing, fulfilment and analytics, where fulfilment needs one message per line item and the caller needs a single confirmation. Which routing components do you use and where does the routing logic live?

Answer

Clarify first: the order-placed event is one message with a header orderId and a body containing line items. The caller (checkout UI) needs one confirmation. Billing needs order total and customer id, one message per order. Fulfilment needs one message per line item. Analytics wants the whole event and does not reply.

Put a content-based router at ingress. It inspects the event type and routes OrderPlaced to an order routing pipeline. That pipeline uses a recipient list to fan out to three destinations: billing, a fulfilment splitter, and analytics. The recipient list is explicit, the routing service knows the three consumers, so no consumer has to filter or re-route.

The fulfilment splitter consumes the whole order and emits one message per line item. Each line-item message carries correlationId = orderId, a sequence number, and the total count. Billing and fulfilment replies go to a replies queue. The aggregator consumes that queue, keys state by correlationId, and waits for one billing ack plus N fulfilment acks. When the expected count is reached, it emits a single OrderConfirmation to the caller's reply-to address.

Correlation identifiers are the join key. The router stamps correlationId on every derived message; the splitter copies it to each line item; replies carry it back. The aggregator never matches on payload content or arrival order. It stores expected count, received sequence numbers, and a deadline. Duplicate replies are idempotent: a repeated seq is ignored.

Trace for orderId=123 with three lines:

  1. OrderPlaced(123, lines=[A,B,C]) arrives on orders queue.
  2. Content-based router routes to recipient list.
  3. Recipient list sends whole order to billing.in, fulfilment.splitter.in, analytics.in.
  4. Splitter emits three messages to fulfilment.line: correlationId=123, seq=1/3, 2/3, 3/3.
  5. Billing replies BillingAck(correlationId=123) to replies.
  6. Fulfilment replies three FulfilmentAck(correlationId=123, seq=n) to replies.
  7. Aggregator expects 4 replies. On the fourth, emits OrderConfirmation(123, confirmed) to caller.reply.
  8. Timeout at 30s: aggregator emits OrderConfirmation(123, partial, missing=[...]) and alerts.

Where routing logic lives: in the integration layer. Broker rules, a routing service, or a lightweight mediator. Consumers subscribe to their own queue and receive exactly the shape they need. Pushing routing into every consumer duplicates the decision, couples consumers to the event schema, and makes a new consumer a change to all producers.

Trade-offs: recipient list is explicit and auditable but the routing service must know consumers; publish-subscribe is more decoupled but harder to reason about. Aggregator adds state and latency; if the caller can tolerate eventual consistency, skip it and let the caller poll or receive separate notifications. Failure modes: missing reply (timeout, partial confirmation), duplicate reply (idempotent seq check), splitter partial failure (at-least-once with dedup), aggregator state loss (persist state or use durable queue with checkpoint). Detect with pending count, age of oldest pending correlationId, timeout rate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design request-reply over asynchronous messaging.

Answer

What I'd say first

Three things decide this design: how long the work takes, whether the client can hold a connection, and whether it can expose an endpoint for a callback. If the work finishes in under a second, async is the wrong tool: do a synchronous call. For work that runs 30 seconds to 15 minutes, I model the request as an operation resource, not a message round-trip, because a broker gives you one-way delivery, not a reply.

The mechanism

Client sends POST /operations with an Idempotency-Key header. The service authenticates, validates, and in a single transaction writes an operation row (state = PENDING) plus an outbox row holding the command. It returns 202 Accepted, Location: /operations/{id}, Retry-After: 1. A worker consumes the command, moves the row to RUNNING, does the work, and writes the result and terminal state (SUCCEEDED / FAILED) in the same transaction as an outbox event. The client polls GET /operations/{id}; that endpoint checks ownership and returns state, progress, and the result once terminal.

State machine: PENDING → RUNNING → SUCCEEDED | FAILED | CANCELLED | EXPIRED. Only RUNNING is cancellable.

The outbox is the part people skip. If the worker commits SUCCEEDED and then crashes before publishing the reply, the client never learns the outcome. Writing the state change and the publish intent in one transaction, then relaying, makes the reply at-least-once instead of best-effort.

Correlation at the transport layer

If your broker has request-reply primitives, use them. AMQP 0-9-1 carries correlation_id and reply_to in the message properties; RabbitMQ's direct reply-to (amq.rabbitmq.reply-to) avoids a broker round-trip per reply. SQS has no native reply: the Temporary Queue Client creates per-client virtual queues. Kafka has no request-reply at all; you'd dedicate a reply topic and partition by correlation ID, which means every consumer sees every reply unless you filter.

Polling vs callback

PollingCallback / webhook
Latencyup to poll interval (1s → 30s backoff)~one network hop
Client requirementoutbound HTTP onlypublic endpoint, TLS, signature verify
Failure handlingclient retries GETyou retry POST with backoff, dedupe on operation ID
Wrong whenhigh-frequency ops, many clientsclient behind NAT or ephemeral

I default to polling with exponential backoff (start 1s, cap 30s, jitter) and offer callbacks as opt-in. Callbacks are the wrong choice when the client is a browser or a short-lived container.

Failure modes

  • Duplicate reply: at-least-once delivery means the terminal event can arrive twice. Dedupe on operation ID; terminal writes are idempotent.
  • Unknown outcome: the client times out. It must reconcile by re-reading the operation, never by resending the command blindly.
  • Cancellation race: cancel arrives after the worker committed SUCCEEDED. Define cancel as best-effort; terminal states win.
  • Poison command: retry N times (say 5) then dead-letter; the operation moves to FAILED with a reason.

Retention: keep terminal results 7 days, operation records 30 days, then expire to EXPIRED. Measure acceptance-to-completion latency as p50/p99 and alert on the count of operations stuck in RUNNING past their timeout.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design a reliable webhook receiver for a SaaS provider.

Answer

Assumptions I'd state first: the provider signs like Stripe. HMAC-SHA256 over {timestamp}.{raw_body}, delivered in a Stripe-Signature header as t=...,v1=...; we own the endpoint but not the sender; delivery is at-least-once and unordered; the business effect must happen exactly once. Stack: one region, Postgres, SQS.

The receiver does four things and nothing else: verify, dedupe, persist, ack. Every business action happens in a worker behind a queue.

Verify. Read the raw bytes before any JSON parser touches them: most frameworks re-serialize the body, changing whitespace and key order, and the HMAC then fails on a legitimate request. Reject when |now - t| > 300s (Stripe's library default tolerance). Compare with hmac.compare_digest, not ==: a byte-by-byte comparison returns as soon as it finds a mismatch, and the timing difference is enough to recover a signature one byte at a time across many requests.

Python
import hmac, hashlib, time

TOLERANCE = 300  # seconds, matches Stripe's default

def verify(raw: bytes, header: str, secrets: list[bytes], now: int | None = None) -> bool:
    now = now or int(time.time())
    fields: dict[str, list[str]] = {}
    for part in header.split(","):
        k, _, v = part.partition("=")
        fields.setdefault(k, []).append(v)
    t = int(fields["t"][0])
    if abs(now - t) > TOLERANCE:
        return False
    signed = f"{t}.".encode() + raw
    for secret in secrets:          # current + previous during rotation
        expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
        if any(hmac.compare_digest(expected, v) for v in fields.get("v1", [])):
            return True
    return False

Trace: header t=1700000000,v1=..., now=1700000400 → delta 400 > 300 → returns False before any HMAC work. Same header with now=1700000100 → delta 100 → HMAC computed and compared. A captured request is therefore dead after five minutes; inside the window, dedupe is the second line of defence.

Dedupe and persist. Insert (provider, event_id) under a unique index; on conflict return 200 immediately. Write the dedupe row and the stored payload in one transaction, so a crash between them cannot lose an event. Ack only after commit. Target p99 ack under 200 ms: providers typically time out at 5–30 s and then retry, so slow acks manufacture duplicates.

Process. Idempotency belongs at the business layer, not the transport. UPDATE orders SET status='paid' WHERE id=$1 AND status='pending' is naturally idempotent; INSERT INTO ledger is not, so it needs event_id as a unique key. Providers do not guarantee order, so never sort by arrival: carry the provider's own sequence or created timestamp and refuse a transition that moves state backwards. Where the provider exposes no sequence, reconcile: poll the API for objects touched in the last 24 h every 15 min and let the API's state win.

choicewins whencost
process synchronously in the requestlow volume, sub-second work, no queue to operatethe provider's timeout becomes your latency budget; one slow downstream call causes retries and duplicates
async via queueany DB write or third-party callyou now own a queue, a DLQ and a replay path
exactly-once deliverynever available end to endat-least-once plus an idempotent consumer is the honest version
failure classexampledetectionaction
invalidbad signature, stale timestamp401 ratedrop; alert on a spike
transientDB down, downstream 503worker exceptionexponential backoff with jitter, cap ~6 attempts
poisonschema change, unknown event typesame event_id failing repeatedlyDLQ, page, replay after the fix

What would change this: if the provider signs without a timestamp, GitHub's X-Hub-Signature-256 has none, the replay window disappears and dedupe on X-GitHub-Delivery is the only defence. That pushes dedupe retention out to ~30 days and makes reconciliation mandatory rather than a backstop.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design a daily partner file exchange.

Answer

What I'd say first

Clarify three things before designing anything: direction (partner→us, us→partner, or both), the cadence and SLA (one file per day, available by 06:00 UTC?), and whether the partner can produce deltas or only full snapshots. I'll assume one-way inbound: the partner publishes one gzipped CSV per day, ~2 GB, ~20M rows, by 06:00 UTC, and we load it into a daily partition of a warehouse table. If any of those is wrong, the design changes.

The design

The landing zone is a directory the partner can write to but not read from ours. They write to incoming/YYYY-MM-DD/ under a temp name, then rename to the final name and drop a manifest. On a POSIX filesystem the rename is the commit point; on object storage there is no rename, so the manifest itself is the commit marker: the receiver only processes a file a manifest names.

Manifest contents: file name, byte size, SHA-256, row count, and control totals (sum of an amount column, count per partition key). That is what makes the load verifiable rather than hopeful.

Receiver state machine per batch:

  1. Read manifest, check batch_id is not already in the load ledger → else skip (idempotent).
  2. Download, verify byte size and SHA-256 against the manifest → mismatch = quarantine, alert.
  3. Parse header, compare column names and types to the expected schema version → drift = quarantine.
  4. Stream rows into a staging table, counting rows and computing control totals.
  5. Compare staging counts and totals to the manifest → mismatch = abort, do not publish.
  6. Swap staging into the daily partition in one transaction, write batch_id to the ledger, emit an ack.

Arithmetic on the window: 2 GB gzipped at a typical 50 MB/s over SFTP is ~40 s of transfer; decompressed to ~10 GB and parsed at 200 MB/s is ~50 s; the load is dominated by the staging insert, so budget 10–15 min end to end and set the SLA alert at 06:15 UTC, not 06:00.

Trade-offs

Snapshot vs delta: a full snapshot is idempotent and self-healing (a missed day costs nothing, you just load the next one) at the cost of 2 GB/day. A delta is ~10x smaller but you now own watermark semantics, out-of-order corrections, and a rebuild path when a delta is lost. Pick snapshot unless volume makes it untenable; if you go delta, keep a weekly full as the recovery anchor.

Push vs pull: the partner pushes to our landing zone (they control timing, we control access) versus we pull from theirs (we control retries). Pull is easier to make reliable because the retry logic is ours.

Failure modes and how you see them

  • Truncated file: byte size or SHA-256 mismatch → caught at step 2, before parse.
  • Duplicate delivery: batch_id already in the ledger → skipped, logged, no double load.
  • Late file: no manifest by 06:15 UTC → alert; downstream jobs wait on the ledger, not the clock.
  • Schema drift: header hash differs from the registered schema → quarantine, page the partner contact.
  • Bad rows: a row fails type or range check → written to a quarantine table with the raw line and reason; the batch loads the good rows only if the contract allows partial, otherwise the whole batch fails.

Retention: keep raw files 90 days, manifests and ledger indefinitely (they are small), and rotate the SFTP key annually with an overlap window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design dead-letter queue operations.

Answer

The 90-second answer

Assume managed queues (SQS, Pub/Sub) or Kafka, at-least-once delivery, and one named owning team per queue. A dead-letter queue is not a graveyard: it is a bounded, owned, replayable quarantine. Three rules decide the design: only terminal failures land in it, every quarantined message carries enough context to be replayed without the original producer, and nothing leaves it except through an idempotent, audited tool.

Terminal vs transient. Transient is a timeout, 429, 503, or connection reset: retry with backoff. Terminal is a schema validation failure, a 400/422, an unknown message type, or a reference to a deleted entity. Retrying a terminal failure just burns throughput, so bound the attempts and move on.

PlatformHow a message lands in the DLQDefaults and limitsOrdering on redrive
SQSRedrivePolicy with maxReceiveCount on the source queue; DLQ must be the same type and regionRetention 1 min–14 days, default 4 days; set DLQ retention longer than the sourceFIFO DLQ keeps group order only if you redrive per MessageGroupId
Pub/Subdead_letter_policy on the subscriptionmax_delivery_attempts 5–100, default 5; DLQ topic must be in the same project and regionNo ordering unless ordering keys are enabled
KafkaNone native: the consumer catches, produces to <topic>.DLT with headersYou own retention; set it to match your replay SLAPer-partition order is lost; key the DLT record by original partition to recover it

Why it exists. Kafka offsets are sequential, so one poison record blocks its partition forever: every other message behind it stalls. SQS standard queues are better but the message returns after each visibility timeout and consumes receive capacity. The DLQ converts a head-of-line block into a bounded backlog.

The envelope. Original message ID, source queue/topic, error class and code, attempt count, first and last failure timestamps, schema version, correlation ID, consumer version. Redact secrets and PII from the payload; store the raw body in object storage with its own retention and keep a pointer.

Redrive. Fix the cause first. SQS gives you StartMessageMoveTask with maxNumberOfMessagesPerSecond: set it deliberately rather than accepting the default. Arithmetic: 2M messages at a self-imposed 200 msg/s is 10,000 s, about 2.8 hours; at 2,000 msg/s it is 17 minutes, but that will saturate the downstream connection pool. Preview by sampling 100 messages against a staging consumer and comparing outcomes before touching the rest. Redrive re-delivers, so dedupe on (business key, message ID) in a store with TTL at least the replay window: otherwise a replayed payment charges twice.

Failure modes and how you see them.

  • Silent expiry. SQS drops messages at retention. Alert on ApproximateAgeOfOldestMessage at 50% of retention, not on arrival.
  • Redrive loop. The message fails again and returns. Detect an attempt count above 2× maxReceiveCount, or DLQ inflow rate rising right after a redrive.
  • Redrive storm. Downstream p99 and pool saturation climb while DLQ depth falls. Throttle and watch consumer lag.
  • Alert fatigue. Per-message alerts on a 10,000-message DLQ page 10,000 times. Alert on inflow rate and oldest age.
  • Ordering break. A FIFO redrive re-injects at the tail, so a later cancel can land before the create it cancels. Detect with a business invariant check, such as a negative balance.

Trade-offs. A shared DLQ is one queue to watch but blurs ownership and lets one team's poison page everyone; per-service DLQs cost more queues and give a clear owner and per-queue retention. Kafka retry topics with backoff preserve order and delay but add topics and lag; a DLT is terminal and needs a human. Auto-redrive is fast and replays poison; manual with approval above a threshold is slower and safer. Retention costs storage, but deleting early loses audit evidence: SQS caps at 14 days, so archive to S3 for a 30-day dispute window.

Reconciliation. After a drain, compare messages moved against the business ledger: 4,812 drained, 4,790 resolved, 22 back in the DLQ. Those 22 need a person, and the count is the report.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Handle a downstream API outage from an integration service.

Answer

Clarify first. Two questions decide the response: can this operation be repeated safely, and is anyone waiting on it? A user-facing read can fail fast and degrade; a durable write must be recorded and reconciled later.

Assumptions I'd state out loud: we own the caller, not the dependency; the dependency is failing with 5xx, timeouts or connection resets, not 4xx; the caller has a 2 s budget inside a 5 s user-facing request.

Core answer. Stop the amplification, then recover. Give every outbound call a deadline shorter than the caller's own, retry only transient failures with jittered backoff, and put a circuit breaker in front so a dead dependency costs a handful of probes instead of thousands of queued requests. Durable work gets persisted with an idempotency key and a truthful "accepted, pending" status; interactive reads get a defined degraded response. Then reconcile the uncertain writes.

Why the mechanisms work.

Jitter. Clients that fail at the same instant share one backoff schedule, so they retry at the same instant: the retry wave lands on a dependency that is just coming back and knocks it over again. Full jitter, sleep = uniform(0, min(cap, base * 2**attempt)), spreads those arrivals across the whole window. AWS's "Exponential Backoff and Jitter" measured full jitter as the best of the strategies it tested for both contention and completion time.

Half-open. A breaker that only opens and closes will flap. After the open window expires, admit a few probes, three is a common choice, and require all to succeed before closing; any failure reopens with a longer cooldown. The probe count is the point: letting all 200 pods probe at once is the outage again.

Idempotency keys. A retry after a timeout is a guess about whether the request was applied. A key the downstream dedupes on turns "maybe applied" into "applied once", which is what makes retrying a POST legal at all. Stripe's Idempotency-Key header is the convention most APIs copy.

Python
# Python 3.12, httpx 0.27
import random, time, httpx

RETRYABLE = {429, 500, 502, 503, 504}

def call(client, req, budget_s=2.0, base=0.1, cap=1.0):
    deadline = time.monotonic() + budget_s
    attempt = 0
    while True:
        try:
            r = client.send(req)
            if r.status_code not in RETRYABLE:
                return r
            hint = r.headers.get("Retry-After")
        except (httpx.ConnectError, httpx.ReadTimeout):
            hint = None
        attempt += 1
        delay = float(hint) if hint else random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
        if time.monotonic() + delay >= deadline:
            raise TimeoutError(f"budget exhausted after {attempt} attempts")
        time.sleep(delay)

Retry-After (RFC 9110 §10.2.3) overrides the computed delay: the server knows when it will be ready and we don't. req must be re-sendable: an httpx Request with a bytes body is, a streaming body is not.

Trace with budget_s=2.0, base=0.1, cap=1.0 and the jitter draws shown:

attemptfails at tcomputed capjitter drawnext try at
10.050.10.070.12
20.150.20.180.33
30.350.40.310.66
40.700.80.551.25
51.301.00.902.20 ≥ 2.0 → raise

Five attempts, then TimeoutError: budget exhausted after 5 attempts. The deadline check runs before sleeping, so the caller never overshoots its budget by a full backoff.

operationretry?why
GET /inventory/{sku}yesidempotent, no side effect
POST /payments + Idempotency-Keyyes, same keydownstream dedupes
POST /payments, no keynomay double-charge
PATCH /orders/{id} (increment)nonot idempotent
400 / 401 / 403 / 404 / 422nodeterministic; retry changes nothing
429 / 503 with Retry-Afteryes, after the hintserver is telling you when
500 / 502 / 504yes, boundedtransient, outcome unknown
connection reset before responseonly with a keyoutcome unknown

Amplification arithmetic: 200 pods × 20 in-flight calls = 4,000 concurrent requests to a dependency already at zero capacity. Three attempts each is 12,000 requests. With a breaker open for 30 s, each pod sends 3 probes per window instead: tens of requests per second across the fleet rather than 12,000 in a burst. Envoy's outlier detection ships with consecutive_5xx: 5, base_ejection_time: 30s, max_ejection_percent: 10, a reasonable starting point to copy.

Failure modes and how you see them: retry storm. Retry volume per dependency spikes while success rate stays flat; breaker flapping (state gauge toggling several times a minute, cooldown too short; half-open herd) probe failures clustered at the cooldown boundary; queue growth. Age of the oldest pending item climbing, not just depth; double-charged mutations. Reconciliation finds two records for one idempotency key, so the downstream isn't deduping; budget inversion. Caller timeout longer than its caller's, so work continues after the user has gone.

Recovery: drain the backlog at a fixed rate rather than as fast as possible, and reconcile every write whose outcome is unknown before re-enabling normal traffic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Integrate a rate-limited external API for bulk synchronization.

Answer

Assumptions: a vendor REST API with cursor pagination and a delta/sync token, quota expressed as requests per window on a shared app credential, and a bulk run of millions of records that takes hours and must survive restarts. If any of those is false the design changes, so say them out loud first.

Core answer (first 90 seconds)

This is a long-running, resumable job that is rate-limited by someone else's clock, not a batch loop. Three things decide the design: the quota's dimension and window, the pagination/delta contract, and where you checkpoint.

  1. Read the contract before writing code. Which dimension is limited: per tenant, per app, per endpoint? What is the window? GitHub's REST API, for example, is 5,000 requests/hour per authenticated user; many vendors are per-minute. What headers come back: Retry-After, X-RateLimit-Remaining, X-RateLimit-Reset? Does the delta token expire, and does the feed emit deletions?
  2. Persist the cursor and the partition. Store (tenant, cursor, delta_token, last_applied_page) durably. A restart resumes from the last durably applied page, not the last fetched one.
  3. Rate-limit globally and fairly. One token bucket per quota dimension, shared across workers, with per-tenant fairness so one large tenant cannot starve the rest.
  4. Retry bounded, with jitter, honoring Retry-After.
  5. Checkpoint after the page is written, idempotently: upsert by natural key so a replayed page is a no-op.

Limiter choice

strategybehaviorwhen it is wrong
token bucketallows burst up to capacity, refills at rateserver enforces a strict fixed window: your burst trips 429 at the boundary
fixed-window countersimple, resets each windowburst at the window edge doubles the effective rate
concurrency semaphorecaps in-flight requestsdoes not bound request rate over time
leaky bucket / queuesmooths to a constant rateyou need burst headroom; adds latency
Python
import time, random

class TokenBucket:
    def __init__(self, rate_per_sec, burst):
        self.rate, self.capacity = rate_per_sec, burst
        self.tokens, self.updated = burst, time.monotonic()

    def acquire(self, n=1):
        while True:
            now = time.monotonic()
            self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
            self.updated = now
            if self.tokens >= n:
                self.tokens -= n
                return
            time.sleep((n - self.tokens) / self.rate)

def backoff(attempt, retry_after=None):
    if retry_after is not None:
        return retry_after          # server told us exactly how long
    return random.uniform(0, min(30, 2 ** attempt))   # full jitter

Trace: rate=2, burst=3. At t=0 tokens=3; three acquire(1) calls leave 0; the fourth sleeps (1-0)/2 = 0.5s. Full jitter spreads retries so a fleet does not synchronize into a thundering herd.

Arithmetic

2M records at page size 100 = 20,000 requests. At 5,000 req/hour that is a 4-hour floor: no amount of parallelism beats it. Ten tenants sharing one app quota means the bucket, not the worker count, sets throughput.

Failure modes and detection

failuredetectionresponse
429 storm429 ratio climbs, Retry-After ignoredhonor the header, back off, alert on 429 ratio
token expiry401 mid-runrefresh credential, resume from cursor
invalid cursor400/410 on page fetchdiscard cursor, full resync for that tenant
missed deletionsreconciliation count driftsperiodic full reconcile
quota changesudden 403 / secondary limitre-read contract, resize bucket

Track quota headroom (X-RateLimit-Remaining), page latency p99, backlog age, duplicate/update counts, and reconciliation discrepancy. Test a long outage plus controlled catch-up before trusting the cursor.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Handle backpressure across an integration pipeline.

Answer

Assume a pipeline with a synchronous HTTP ingress, an async worker pool, and a downstream database with a connection pool of 20. The database can handle 4000 queries/s. Ingress receives 5000/s. Queue grows at 1000/s. With a 200ms p99 SLO, max queue depth is 800. So we set queue capacity to 800 and shed or return 429 when full.

The core is to bound every queue and propagate backpressure upstream before it becomes a latency problem. Measure arrival rate, service rate, queue depth, and queue age at each stage. Use Little's Law: L = λW. If you know service rate μ and target latency W, max queue depth L = μ * W. For our example, μ=4000/s, W=0.2s, L=800. So when queue depth exceeds 800, you must either block producers, shed work, or throttle producers.

Blocking is simplest: the producer waits until the queue has space. Use it when the producer can tolerate latency and the downstream is critical. But it can cause thread pool exhaustion or deadlock if there's a cycle. Dropping is better when work is idempotent or can be retried. Return HTTP 429 with Retry-After. But if clients retry immediately, you get a retry storm. Throttling is a softer version: reduce producer rate. Batching increases throughput but adds latency; use it when the latency budget allows. Priority helps when you have mixed criticality, but can starve low-priority work.

Failure modes: Retry storm: detect by retry rate > 10% of requests, or queue depth growing despite autoscaling. Oscillation: autoscaler adds instances, queue drains, removes instances, queue spikes again. Detect via sawtooth pattern in instance count and queue depth. Operational cost: increased latency, dropped requests, over-provisioning. To avoid, use a cooldown period and scale on queue age, not just depth. Also, preserve durable accepted work: if you accepted a request, you must eventually process it. Shed only safe classes.

Here's a trace of a bounded queue with capacity 3, arrival 2/tick, service 1/tick. The queue stabilizes at depth 2 and sheds 1 per tick. The shed count is the backpressure signal.

Python
from collections import deque

capacity = 3
q = deque()
arrivals_per_tick = 2
service_per_tick = 1
shed = 0
served = 0

for t in range(5):
    for _ in range(arrivals_per_tick):
        if len(q) < capacity:
            q.append(t)
        else:
            shed += 1
    for _ in range(service_per_tick):
        if q:
            q.popleft()
            served += 1
    print(f"t={t}: depth={len(q)}, shed={shed}, served={served}")

Output:

t=0: depth=1, shed=0, served=1
t=1: depth=2, shed=0, served=2
t=2: depth=2, shed=1, served=3
t=3: depth=2, shed=2, served=4
t=4: depth=2, shed=3, served=5

This shows that after t=2, queue depth stabilizes at 2 and shed increases by 1 per tick. If we instead blocked producers, they would see increased latency. If we throttled producers, they would reduce arrival rate.

StrategyMechanismWhen to useFailure mode
BlockingProducer waits until queue has spaceDownstream is critical, producer can tolerate latencyDeadlock if circular dependency; thread pool exhaustion
DroppingReject new work when queue fullWork is idempotent or can be retried; protect downstreamLost work if not durable; retry storm if clients retry immediately
ThrottlingReduce producer rate via 429/Retry-AfterProducers are cooperative and can back offThundering herd if Retry-After ignored
BatchingAccumulate multiple items per downstream callLatency budget allows; downstream supports batchIncreased latency; batch size limits
PriorityServe high-priority work firstMixed criticalityStarvation of low-priority work

If you're using Kafka, the consumer's max.poll.records defaults to 500; if processing each record takes 10ms, a poll can take 5s, which is under the default max.poll.interval.ms of 300000ms, but it increases latency. SQS visibility timeout defaults to 30s; if your processing takes longer, the message becomes visible again and can be processed twice. HTTP 429 with Retry-After is standard. gRPC uses HTTP/2 flow control with a default window of 64KB per stream.

The decision point: if the downstream is critical and producers can wait, block. If work is idempotent and you must protect the downstream, drop. If producers are cooperative, throttle. Always bound the queue and propagate the signal upstream.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Choose orchestration or choreography for account onboarding.

Answer

What I'd say first

"Before I choose, I need three numbers: how many distinct steps and owning teams, the end-to-end SLA, and whether a human approves anything. One team, five steps, no human: choreography is fine. Four teams, a regulatory clock, and a manual KYC review: I default to orchestration."

For account onboarding I default to orchestration, because onboarding is one business outcome with a deadline and an audit trail, and choreography makes that outcome emergent rather than owned.

Why

Orchestration puts a durable coordinator in charge: a Temporal workflow, a Step Functions state machine, a Camunda process. Each step is an activity with its own retry policy and timeout, state is queryable ("where is account 4471?" is one read), and compensation is explicit: if credit declines after you reserved an account number, the coordinator calls the release step.

Choreography has services publish and subscribe to events: Kafka topics, EventBridge rules. No component knows the whole flow. Team autonomy is real: a team ships a new reaction without touching anyone else's code. But the flow exists only in the union of subscriptions.

OrchestrationChoreography
StateOne durable recordReconstructed from the event log
Adding a stepEdit the workflowNew subscriber, no central change
CompensationExplicit, orderedWhoever subscribed must remember
"Why is 4471 stuck?"One workflow queryStitch logs across N services

Failure modes and how you see them

Choreography:

  • Event loop: A emits, B reacts and emits, A reacts again. Detect with a hop-count or correlation-id depth metric; alert when one onboarding's chain exceeds ~12 hops.
  • Silent schema break: a producer renames a field, the consumer drops the event. Detect with consumer-side contract tests and a dead-letter queue that pages when depth > 0.
  • Diagnosis cost: every stuck account is a cross-service log hunt by correlation id.

Orchestration:

  • Coordinator is a dependency, if the workflow service is down, onboarding stops. Detect via schedule-to-start latency on the task queue.
  • Stuck workflow: an activity that never returns holds the workflow open. Detect via workflow-task backlog and per-activity timeout alarms.
  • Versioning: a workflow running for days is pinned to the code version it started on.

Arithmetic

Six sequential steps, each 99.9% reliable: 0.999^6 ≈ 99.4% end-to-end, so ~6 in 1,000 onboardings fail and need manual repair. Give each step 3 retries and per-step failure falls to 0.001^3 = 1e-9; end-to-end ≈ 99.9999994%. That is the case for retries living in a coordinator that owns them, not in six teams' ad hoc code.

Trace: orchestrated compensation

  1. reserve_account_number → 200, account 4471 reserved
  2. run_kyc → pass
  3. credit_decision → decline
  4. coordinator invokes compensation: release_account_number(4471) → 200
  5. notify_applicant → queued

End state: workflow status FAILED_COMPENSATED, no orphaned reservation. In choreography the same decline is just an event; whether the reservation is released depends on someone having subscribed.

When not to

Choreography wins when reactions are few, stable, and each service already owns its trigger: "on account.created, send welcome email" and "on account.created, create CRM record." Two subscribers, no ordering, no compensation. Don't mix both without a boundary: pick one owner per business outcome.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Design a multi-service checkout saga.

Answer

Clarify, then assume. Four services: order, inventory, payment, shipping. Payment goes to an external PSP, so no database transaction spans it. I'll assume each service owns its own store, we have Kafka and Postgres, and the hard requirement is: never capture money for inventory we didn't reserve. Target p99 checkout under 2s, and every saga reaches a terminal state or a parked state within 30s.

Core answer: orchestrate, don't choreograph. A single order-service orchestrator owns a saga row in Postgres. saga_id, state, current_step, deadline_at. Each step is a command with a 1.5s timeout, 3 attempts, 100ms/200ms backoff: a 4.8s budget per step, 19.2s across four steps, leaving roughly 10s for compensation inside the 30s deadline. Choreography would spread that state across four services' event logs. You'd drop the coordinator, but you'd also lose the one place that can answer "where is order 8123 right now", which is the first thing support asks and the only way to reconcile.

Persist before you send. The state transition and the outgoing command commit in one local transaction: update saga, insert into outbox. A relay polls outbox every 100ms, publishes to Kafka, marks sent=true. Without this, a crash between commit and publish strands the saga in AWAITING_INVENTORY with no command in flight and nothing to retry. With it you get at-least-once delivery, which pushes the burden onto consumers being idempotent.

Idempotency is a unique key, not a flag. Every command carries saga_id and step_id. Each participant has a table with a unique constraint on (saga_id, step_id) that stores the reply. A replay hits the constraint, returns the stored reply, and increments saga_duplicate_commands_total. That counter is the detection signal: if it climbs, your relay is redelivering and you look at consumer lag, not at saga logic.

#StepServiceCompensationReversible?
1ReserveInventoryinventoryReleaseInventoryyes
2AuthorizePaymentpayment / PSPVoidAuthorizationyes, inside the auth window
3CreateShipmentshippingCancelShipmentonly before carrier handoff
4ConfirmOrderorder—terminal

Failure modes, and what you watch for each.

  • Late reply after timeout. The orchestrator already moved to COMPENSATING. The reply arrives with a step_id whose state is no longer AWAITING; discard it but count saga_late_replies_total. If that exceeds ~0.1% of sagas, your 1.5s timeout is tighter than the PSP's p99 and you're compensating payments that were about to succeed.
  • Coordinator restart. State is durable, so recovery is a scan every 30s for sagas that are non-terminal with updated_at older than twice the step budget. The relay resumes from sent=false rows. No in-memory timers survive, so nothing depends on them.
  • Participant down. A circuit breaker opens after 5 consecutive failures; the step budget expires and the saga compensates. If compensation itself fails, the saga goes to PARKED and pages a human. Never retry compensation forever: a stuck void is money held on a customer's card, and an infinite retry loop hides it.
  • Authorized but void fails. This is the case you cannot undo. Reconcile hourly: pull the PSP's open authorizations and diff against saga rows in COMPENSATING. A mismatch is a hold with no matching saga. Retry the void; if the authorization already captured, issue a refund instead. That job is the only thing that catches a lost void, because nothing else in the system will ever retry it.

Trade-off. Orchestration costs a highly available coordinator and a saga table that grows: partition it by month. Choreography earns its keep when steps are genuinely independent and nobody needs the aggregate view. Checkout isn't that: the customer is watching a spinner, and support needs one row to read.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Migrate a legacy integration with the Strangler Fig pattern.

Answer

Assume the legacy integration is a synchronous request/response API over a shared relational database, and consumers call it directly. What I'd say first: put a routing facade at the caller-facing boundary, migrate one slice at a time behind it, keep exactly one writer per entity, and delete the legacy path only when consumer telemetry shows zero traffic.

The facade is the whole trick because it's the only place you can change which implementation serves a request without touching a consumer. That forces the seam to be a contract boundary, an endpoint or a message type, not a database transaction. If the legacy code updates two entities in one transaction and you split them across services, you've broken atomicity and no facade repairs that. That slice isn't migratable until you keep the two together or wrap them in a saga.

Write authority decides whether the migration lands. Dual-writing from application code to legacy and new stores has no atomicity across the two writes: a crash between them leaves the stores divergent and nothing notices.

approachmechanismcost
app-level dual writehandler writes legacy, then newdivergence window = gap between writes; no detection
transactional outboxlegacy txn writes row + outbox row; relay publishesrelay lag; consumers must be idempotent
CDC (Debezium on Postgres logical replication)tail legacy WAL, publish to new storereplication slot lag; couples you to the legacy schema

Shadow mode, traced for a GET /accounts/{id} slice:

  1. Facade calls legacy, returns the legacy response. Caller latency unchanged.
  2. Facade fires the same request at the new service on a bounded executor: say 50 ms timeout, 200 in-flight cap.
  3. Comparator diffs status, body fields and latency, writing a mismatch record keyed by endpoint and field.
  4. Cut over when mismatches are zero across N requests and the new service's p99 fits the budget.

The cap is not optional. The new service reads the legacy database during transition, so uncapped shadow traffic doubles read load on the legacy DB and exhausts its connection pool.

Failure modes and how you see them:

  • Split authority. Two writers to one entity diverge. Detect with an hourly reconciliation job comparing per-entity checksums; alert on any mismatch. At 500 writes/s, one hour is 1.8M rows per run: that's the cost of not having a single writer.
  • Facade ossification. Routing rules accumulate and the facade becomes a permanent hop. Detect by tracking facade p99 minus direct-call p99 and the rule count; if it's still routing after the last slice, it's now infrastructure.
  • Shadow saturation. Legacy DB pool wait time climbs and active connections pin at the max. Detect on pool wait, not error rate: saturation shows up as latency first.
  • Silent contract drift. The new service returns 200 with different field semantics. Detect with consumer-driven contract tests (Pact) plus the shadow comparator; a green status code proves nothing.

When not to use it: one consumer you control, or a legacy system being retired this quarter. Then a facade is a hop you'll delete anyway: change the caller directly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Evolve an event contract used by unknown consumers.

Answer

Core answer (first 90 seconds)

Assume the contract is a log topic (Kafka or equivalent) carrying Avro, Protobuf or JSON Schema payloads, and you genuinely cannot enumerate every consumer. Then compatibility is not a convention you ask people to follow: it is a property the schema registry checks at registration time.

"I'd register the schema with an explicit compatibility level, default BACKWARD, and let the registry reject any producer change that breaks it. Additive optional fields with defaults are the only routine change. Removing a field, changing a type, or repurposing an enum value is a new event type, dual-published, with retirement gated on measured consumer migration rather than a calendar date."

Why the mechanisms work

Avro resolves reader against writer schema at read time. A new reader schema can read old data if every added field has a default: that is BACKWARD. A new writer schema stays readable by old readers if removed fields had defaults: FORWARD. FULL requires both. Confluent Schema Registry enforces this at registration, and BACKWARD is its default level. Protobuf gets the same guarantee from a different mechanism: field numbers are the identity, and unknown fields are preserved, so adding a field is safe and removing one requires reserved 5; to stop the number being reused. JSON Schema has no resolver at all: compatibility is only as good as consumers ignoring unknown properties, so it needs a contract test in CI.

ChangeAvroProtobufJSON Schema
add optional field with defaultBACKWARD okok, new field numberok only if consumers ignore unknown props
remove fieldFORWARD onlyreserve the numberbreaking
repurpose an enum valuebreaking, silentbreaking, silentbreaking, silent

Trade-offs: new event vs translation path

Choose a new event type when the meaning changes: a translation layer cannot invent semantics it was never told. Choose a translation path (a consumer-side adapter, or a stream processor rewriting old→new) when the shape changes but meaning is stable and you have more consumers than you can coordinate redeploys. Translation costs an extra hop and a second schema to maintain forever; it earns its keep only when the consumer count exceeds the number you can actually reach.

Failure modes and how you detect them

  • Enum repurposing. An old consumer's switch hits its default branch and silently drops the event. Detect by counting events landing in the consumer's unknown_enum branch; alert on any nonzero.
  • Unit change (epoch seconds → millis). Detect with a range guard: values above 1e12 are millis. A producer still emitting seconds shows up as a 1000× drop in a duration histogram.
  • Nullable field made required. Consumers NPE. Detect with a per-consumer-group deserialization/validation error rate, not just producer-side send errors.
  • Replay past retention. Kafka's default log.retention.hours=168 (7 days). A consumer down longer than retention cannot replay the version it missed, so any replay promise requires retention to exceed maximum consumer downtime.

Retirement arithmetic

With 40 consumer groups and the slowest shipping quarterly, a 90-day dual-publish window covers it. Gate retirement on zero committed offsets on the old topic for 14 consecutive days, measured per group: never on a date someone picked in a planning meeting.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Build reconciliation for an event-driven projection.

Answer

Before designing anything I would ask which side is authoritative and what a wrong projection costs. My assumption here: a Kafka topic is the event log, the projection is a Postgres read model written by one consumer group, and the log is the best available history, not the source of truth, because Kafka's default log.retention.hours=168 deletes a week of segments and the default log.cleanup.policy=delete, so anything older than retention cannot be replayed at all.

Three layers, at different costs.

layercadencecomparescostdetection
watermark30 sapplied offset vs topic endone row30 s
bucket sweephourly, previous hourper-hour count, sum, min and max event idsread replica, seconds per bucketunder 1 h
Merkle sweepweekly, off-peakhash tree over id rangestwo full scansone week

The watermark is the part teams get wrong. Do not compare wall clocks. Have the consumer write the Kafka offset it just applied into a projection_watermark row inside the same transaction as the projection write, so reading the projection and its watermark is atomic. Committed offsets from kafka-consumer-groups.sh --describe tell you what the consumer claimed, not what the sink durably holds. After a crash between sink commit and offset commit they disagree, and that gap is exactly what reconciliation exists to find.

The hourly sweep, run over the projection and over the same hour replayed into a scratch table:

SET TIME ZONE 'UTC';
SELECT date_trunc('hour', event_time) AS bucket,
       count(*)                      AS rows,
       sum(amount_cents)             AS cents,
       min(event_id)                 AS lo,
       max(event_id)                 AS hi
FROM orders_enriched
WHERE event_time >= '2026-02-01T00:00:00Z'
  AND event_time <  '2026-02-02T00:00:00Z'
GROUP BY 1 ORDER BY 1;

Bucket on event_time carried inside the event, never on write time. Bucket by write time and every late arrival slides a row between buckets, so you page on a false mismatch every hour.

Hypothetical numbers from one sweep: 24 buckets, 23 match. Hour 14 shows 481,203 rows and 3,109,884,120 cents in the projection, against 481,206 rows and 3,109,889,950 on replay, so three rows and 5,830 cents short. An anti-join on event_id inside that hour finds the three. Two carry offsets above the watermark: in flight, not divergent, so the comparer must exclude the trailing bucket. The third has a committed offset and no row, which is a write lost after the offset commit.

Repair is replay into a separate reconciler consumer group over offsets [a,b] with an idempotent upsert on event_id, then re-running the same bucket check. Never patch rows by hand. Two cases make replay impossible and need a different plan: a compacted topic cannot reconstruct intermediate states, and a divergence older than the retention window has no segments left, while offsets.retention.minutes defaults to 10080, so a group that has sat idle a week loses its committed offsets too. Past that point, rebuild from the owning service into a shadow table and swap it in.

What I expect to actually break: a new event type the projection silently ignores, where counts agree and sums do not; a non-idempotent upsert on redelivery, where sums run high and the row set still looks right; and a backfill that never lets the trailing window settle, so every sweep reports garbage.

Run the sweep on a replica, batch by bucket, and abort if replica lag exceeds 10 s. Alert on watermark lag above 60 s for five minutes, and on any bucket discrepancy older than 24 hours.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Prevent tenant data leakage in a shared integration pipeline.

Answer

What I'd say first

Assume a multi-tenant SaaS where tenants are paying customers with contractual isolation, and the pipeline is async: ingest → transform → sink, sharing a Kafka cluster, an object store, and a Postgres state store. The core answer: tenant identity is established once, at the authenticated edge, from the caller's credential or verified subscription, never from a field in the payload, and then carried as an immutable, signed attribute that every stage re-checks. Authorization happens before durable acceptance, so a message that fails the tenant check never lands in a queue or a table.

Why leakage actually happens

The failure is almost never a missing tenant column. It's a tenant variable resolved once per batch instead of once per record, a cache key that omits the tenant, an idempotency key that collides across tenants, or a DLQ redrive that replays a message under the operator's context rather than the original tenant's. Kafka sharpens this: ACLs are per topic, consumer group, cluster and transactional ID. There is no per-record ACL. If two tenants share a topic, isolation is enforced by your consumer code, and one bug is a breach. Compose idempotency keys as sha256(tenant_id || operation || client_key) so tenant A's key can never dedupe tenant B's message.

A trace

Producer keys by order_id, so acme and globex records land in the same partitions. Consumer polls 500 records: 480 acme, 20 globex. The consumer hoists tenant = records[0].tenant above the loop. It writes all 500 to s3://sink/acme/2024-06-01/batch-0007.jsonl. Globex's 20 records, 4% of the batch, now sit in acme's prefix, and acme's export job reads them. Fix: key by tenant_id so a partition is single-tenant, and assert every record in a batch shares the tenant, failing the batch otherwise.

Choosing the boundary

boundaryisolationcostchoose when
shared topic + per-record checkcode-enforcedlowestinternal tenants, low blast radius
topic per tenantbroker-enforced ACLsN topics, more metadata and rebalanceexternal tenants, contractual isolation
cluster per tenantfullhighestregulated or largest tenants

Detection and cost

Reconcile per-tenant record counts and checksums at each hop; a mismatch pages. Plant a canary record per tenant and alert if it appears under another tenant's prefix. In Postgres, RLS with USING (tenant_id = current_setting('app.tenant_id')::uuid) is a backstop, but it is bypassed by the table owner and superuser unless you FORCE ROW LEVEL SECURITY. Keep tenant_id out of Prometheus labels: 10,000 tenants × 20 metrics is 200,000 active series, which will take down the scrape.

Trade-offs

Topic-per-tenant at 1,000 tenants × 3 topics is 3,000 topics; controller metadata and consumer-group churn grow, and rebalances get slower. Shared topic plus a per-record assertion is cheap and fine when a leak is a bug, not a breach. Cluster-per-tenant is for the handful of tenants whose contract says so. Don't try to encrypt your way out of this: encryption at rest doesn't stop a misroute, because the sink writes with its own credentials.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design integration observability without logging sensitive payloads.

Answer

In an interview, I'd start by clarifying the integration patterns: are we dealing with asynchronous messaging (Kafka, SQS), synchronous HTTP calls, or both? I'll assume a multi-tenant SaaS with Kafka for async and gRPC for sync, and payloads contain PII like email and credit card numbers. The core answer: propagate a correlation ID and trace context in message headers or HTTP headers, never in the payload. Log only metadata: IDs, operation, tenant pseudonym, schema version, processing stage, outcome, latency, and error taxonomy. Redact or hash any field that could be sensitive. Use metrics for aggregate health, traces for flow, and structured logs for discrete events. Bound cardinality, sample traces, set retention, synchronize clocks, and audit operator queries.

Why this works: the correlation ID is generated at the trust boundary (API gateway or message producer) and propagated. For async, we inject it into Kafka headers. For sync, we use W3C Trace Context's traceparent header. This lets us stitch a trace across services without touching the payload. Redaction is enforced by an allowlist: only fields explicitly marked safe are logged. For example, we log tenant_id as a pseudonym (HMAC of the real ID) and never log email or card_number.

Trade-offs: full payload logging would make debugging easier but risks PII leaks and storage costs. Metadata-only logging requires discipline but is safer. For sampling, head-based sampling (e.g., 1% of traces) is cheap but may miss rare errors; tail-based sampling captures all errors but needs buffering. For context propagation, synchronous calls are automatic; asynchronous requires explicit header injection, which is a common failure point.

Failure modes:

  • Missing correlation ID: traces break at service boundaries. Detection: monitor for root spans in services that should always be downstream; alert if >1% of spans lack a parent.
  • Redaction leak: PII appears in logs. Detection: automated regex scanning for credit card patterns, plus canary tokens (e.g., a fake SSN) injected into test payloads; alert if found.
  • Cardinality explosion: metric labels like user ID cause time series to explode. Detection: monitor active time series count; alert on >10% daily growth. For example, 100 tenants × 50 operations × 20 error codes = 100,000 series, which is fine; adding 1M user IDs would be 100 billion series, which is infeasible.
  • Clock skew: negative latencies or out-of-order events. Detection: compare NTP offset across hosts; alert if >100ms.
  • Sampling miss: rare errors not captured. Detection: tail-based sampling for error spans, or always sample errors.

Artefacts: Here's a Python snippet using confluent-kafka 2.3.0 to inject context into headers:

Python
from confluent_kafka import Producer
import uuid

def produce(topic, key, value, trace_id, parent_span_id):
    headers = [
        ('traceparent', f'00-{trace_id}-{parent_span_id}-01'),
        ('correlation_id', trace_id),
        ('causation_id', parent_span_id),
        ('schema_version', '1.2.0'),
        ('tenant_pseudonym', 't_abc123')
    ]
    producer.produce(topic, key=key, value=value, headers=headers)

And a table comparing signals:

SignalAnswersCardinality riskRetentionSampling
LogsWhat happened to this message?High if payload logged30 daysNone
MetricsHow many failed?High if tenant/user in labels13 monthsAggregated
TracesWhere did time go?Medium (span attributes)7 daysHead-based 1%

Finally, synchronize clocks with NTP and don't rely on timestamps for ordering; use sequence numbers or causal ordering. Audit operator queries by logging who queried what and when, and test that failure diagnosis works using metadata alone: e.g., can you find a lost message using only correlation ID and error code? If not, your observability is incomplete.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Recover an asynchronous integration after regional failure.

Answer

Assumptions I'd state before answering. The integration is Kafka-based, at-least-once, consumers write into a downstream store. Region A (brokers + consumers) is gone; region B holds a replicated copy. The business tolerates duplicate effects but not lost ones. Targets: RTO 30 min, RPO 5 min. If any of that is wrong, the plan changes: say so and ask.

Core answer. Recovery is four ordered steps, not "restart consumers": (1) establish a single writer, (2) resume from a known offset, (3) drain under a throttle, (4) reconcile, and only then fail back. Skipping (1) produces duplicate effects; skipping (4) produces silent divergence.

Step 1: fence the old region. Kafka's group coordinator fences within one cluster via the generation number, but across two clusters it does not. MirrorMaker 2 replicates offsets into mm2-offset-syncs.<cluster>.internal and checkpoints into <cluster>.checkpoints.internal, and it will not translate consumer group offsets unless sync.group.offsets.enabled=true (default is false). So fencing has to come from outside: a lease row in a control DB with a monotonically increasing epoch. Every consumer checks lease.epoch before applying and refuses to write if it is stale. Region A producers are fenced the same way.

Step 2: resume from a known position. With enable.auto.commit=true (the default) offsets are committed on a timer, so the resume point is approximate and you will re-read a window. That is fine if effects are idempotent; it is fatal if they are not. Dedupe on (topic, partition, offset) or a business key with a unique constraint:

Python
# Python 3.12, confluent-kafka 2.4
def handle(msg, db, lease):
    if lease.epoch < REQUIRED_EPOCH:
        raise FencedError                 # another region owns this partition
    key = (msg.topic(), msg.partition(), msg.offset())
    with db.transaction():
        r = db.execute("INSERT INTO applied(key,payload) VALUES(%s,%s) "
                       "ON CONFLICT DO NOTHING", (key, msg.value()))
        if r.rowcount == 0:
            metrics.incr("dedupe.hit")    # expected replay, not an error
            return
        apply_effect(db, msg.value())
    consumer.commit(msg)                  # commit only after the effect is durable

Step 3: throttle the drain. Size the rate against downstream headroom, not against how fast you want to be done. If downstream p99 is 40 ms at 2000 msg/s steady state and the backlog is 4.2M messages, draining at 1.5x steady state (3000 msg/s) finishes in ~23 min and pushes p99 to roughly 95 ms. Draining at 10x finishes in 3.5 min and saturates the connection pool, which cascades into every other caller of that store.

Step 4: reconcile, then fail back. Compare per-partition produced counts against applied counts minus dedupe hits. Failback is a second failover and needs the same fencing.

Failure modes and how you see them.

failuresymptomcost
split-brain: two groups applyingdedupe.hit climbing steadily, not just in the replay windowdouble-charged customers; manual reconciliation
offset divergencelast committed offset per partition below source high-water mark after drainsilent data loss, found weeks later
poison messagelag flat on one partition while others drainRTO blown on one partition
downstream saturationp99 40→180 ms, pool exhausted at 20 connectionscascading failure into other services

Trade-offs. Replay from the last checkpoint is fast with a small gap risk; replay from the beginning is safe but reprocesses hours and demands full idempotency. Warm standby fails over in minutes but must have been kept warm and fenced; rebuilding from object storage takes hours and cannot split-brain. Pick by whether your RPO is met by the checkpoint and whether the downstream is genuinely idempotent.

Worked trace (figures hypothetical).

t+0:00  region A fails; alert on flat consumer lag + unreachable brokers
t+0:02  on-call takes lease in control DB, epoch 41 -> 42; A producers fenced
t+0:05  verify B brokers healthy, min.insync.replicas satisfied
t+0:08  start B consumers at epoch 42, resuming from translated offsets
t+0:08  drain 4.2M backlog at 3000 msg/s; p99 40 -> 95 ms, within budget
t+0:20  lag 0; reconcile: produced 4.2M, applied 4.2M, dedupe hits 11,340
t+0:25  failback: stop B, epoch -> 43, restart A, confirm lag 0 again

The 11,340 dedupe hits are the expected replay window from approximate offset translation. A number that keeps climbing after the window closes is the split-brain signal.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Test an integration before production release.

Answer

Assumptions I'd state before answering

Event-driven integration: service A writes to a Postgres outbox in the same transaction as its business row; a relay publishes to Kafka 3.6; service B consumes with enable.auto.commit=false, dedupes on a business key, and calls one downstream HTTP API. At-least-once, no XA. If the integration is actually synchronous request/response, half of this changes, so I confirm the shape before writing a test.

What I test, in order

  1. Contract at each boundary. Producer schema against consumer expectation, and the downstream HTTP contract. I use Pact or a JSON Schema check in CI so schema drift fails in seconds without a broker. This catches the "field renamed, consumer silently drops it" class.

  2. Fault at commit boundaries. The interesting failures are all "the process died between two writes." I inject with Toxiproxy for network faults and by killing the container mid-batch.

  3. Recovery. Can it drain a backlog and reconcile to the source of truth.

Failure modes, injection, detection

FailureInjectDetectCost if missed
Duplicate deliveryReplay same offset; publish same key twiceDedup table has 1 row; downstream called onceDouble charge or double email
Poison messagePublish payload failing schemaDLQ depth > 0 within retry window; partition lag resumesHead-of-line block
ReorderPublish key A, then B, then A againLast-write-wins state matches event timestampsStale state overwrites fresh
Outbox relay stallStop relay for 60sOldest unpublished row age > thresholdSilent data-loss window
Consumer crash mid-batchSIGKILL after DB write, before commitOn restart, no duplicate side effectPartial batch, no ack

The arithmetic that decides the DLQ threshold

Kafka 3.6 consumer defaults: max.poll.interval.ms=300000, session.timeout.ms=45000, delivery.timeout.ms=120000. If a poison message retries 5 times with backoff 1+2+4+8+16 = 31s, and the partition runs at 2,000 msg/s, that is roughly 62,000 messages queued behind it. So the retry budget is a throughput decision, not a nicety: I set it so worst-case stall stays under max.poll.interval.ms, or the consumer gets evicted and the whole partition rebalances.

Trade-offs

Contract tests (Pact) run in CI in seconds and need no broker, but they cannot see ordering, broker config, or backpressure. Testcontainers plus Toxiproxy give real fault injection but are slow and flaky unless you pin versions. One staging end-to-end run catches wiring the other two miss. I do not run full load tests every release, only when throughput-affecting code changes, because a 30-minute soak per PR is a tax nobody reads.

What I skip

Kafka's replication, the HTTP framework's retry, TLS. Vendor surface. I test my code's behaviour at the seams.

Detection in production

Consumer lag (kafka-consumer-groups --describe, LAG column), DLQ depth, outbox oldest-row age, reconciliation diff count. Assert business state, order count and ledger balance, not just broker metrics, because a green broker metric with a wrong ledger is the failure that ships.

Curated: · Written: · Reviewed:

Difficulty: Hard