Making a Kafka-to-Postgres Payment Consumer Safe Under Retries
System DesignModel answerLast updated
Fix lost security context in async tasks, duplicate ledger writes after Kafka redelivery, and unsafe shared metrics maps in a Java 17 / Spring Boot payment consumer.
Scenario: Hardening a payment-event consumer
A Java 17 / Spring Boot 3 service reads card authorization events from a Kafka topic named payment-authorizations. For each event it calls an internal risk-scoring REST API asynchronously, then writes the resulting transaction to PostgreSQL.
Load testing exposed three defects:
- Missing credentials downstream. Calls made from async tasks get
401 Unauthorizedbecause the SpringSecurityContextis not present on the worker threads. - Double debits. During network instability and consumer-group rebalances, the same Kafka record is handled more than once and the ledger receives duplicate debit rows.
- Corrupt metrics. A shared in-memory metrics store built on a plain
HashMapsometimes shows wrong counts or throwsConcurrentModificationException.
Describe how you would diagnose and fix each problem, with concrete implementation choices.
What to cover
A. Security context across threads
- Why does
SecurityContextHolder.getContext()come back empty inside a task started withCompletableFuture.supplyAsync()or a customThreadPoolTaskExecutor? - Give two sound ways to carry the caller's credentials into worker threads. Explain the specific danger of
MODE_INHERITABLETHREADLOCALwhen threads are pooled.
B. Kafka delivery and idempotency
- Compare
enable.auto.commit=truewith Spring Kafka'sAckMode.MANUAL_IMMEDIATE. Why does at-least-once delivery produce duplicates around rebalances? - Design an end-to-end approach so redelivered records can never produce a second database write. Name the constraints and the check you would use.
- How do you deal with an unprocessable "poison pill" record without stalling the partition forever?
C. Concurrency and the database/Kafka boundary
- Compare
ConcurrentHashMap,Collections.synchronizedMap()and an explicitReentrantLockfor a read-heavy, highly concurrent metrics store. - Suppose the database transaction commits but the Kafka offset commit then fails. What happens, and how do you handle the inconsistency between the two systems?
Hints
Hint 1
A ThreadLocal belongs to exactly one thread. Ask which thread the authentication was stored on and which thread runs the async task, then ask when an inheritable thread local is copied.
Hint 2
Treat the database as the single referee for duplicates: record a stable business identifier under a uniqueness constraint in the same transaction as the ledger write, and still acknowledge duplicates.
Hint 3
You cannot make a DB commit and a Kafka offset commit atomic. Make redelivery harmless instead, and use an outbox table if the service also needs to publish events after its DB write.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
All three defects have the same root: hidden assumptions about threads and about exactly-once behavior. The fixes are to make thread-bound state explicit, to accept that Kafka redelivers and make processing idempotent, and to use concurrency primitives that match the access pattern.
A. Security context across threads
Why it is empty. By default SecurityContextHolder uses MODE_THREADLOCAL, so the Authentication lives in a ThreadLocal on the thread that handled the original request. supplyAsync without an executor runs on ForkJoinPool.commonPool(). A ThreadPoolTaskExecutor runs on its own workers. Neither worker ever had the context set, so the REST client has no token and the callee answers 401. The same applies to MDC and to transaction state, so async work also runs outside the caller's @Transactional scope.
Option 1: wrap the executor. DelegatingSecurityContextAsyncTaskExecutor snapshots the context when a task is submitted, installs it on the worker, and clears it in a finally afterward.
@Bean
AsyncTaskExecutor enrichmentExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(16);
pool.initialize();
return new DelegatingSecurityContextAsyncTaskExecutor(pool);
}
// always pass it explicitly
CompletableFuture.supplyAsync(() -> riskClient.fetch(id), enrichmentExecutor);
Option 2: a TaskDecorator (or wrapping individual Runnable/Callable objects). This also lets you propagate MDC or trace IDs in the same place.
pool.setTaskDecorator(task -> {
SecurityContext ctx = SecurityContextHolder.getContext();
return () -> {
try { SecurityContextHolder.setContext(ctx); task.run(); }
finally { SecurityContextHolder.clearContext(); }
};
});
Why MODE_INHERITABLETHREADLOCAL is risky with pools. The value is copied only when a thread is created. A pooled worker is created once, by whichever request happened to grow the pool, and keeps that user's context indefinitely. Later tasks for other users then run as the wrong principal, which is a privilege-escalation and audit problem. The parent and child also share one mutable context object, and nothing clears it between tasks. Per-task capture and clear is the only safe model.
Consumer note. A Kafka listener has no inbound HTTP request, so there is no user to propagate. The service should call downstream as itself, for example with an OAuth2 client-credentials token, rather than fabricate a user context.
B. Kafka semantics and idempotency
Commit modes.
enable.auto.commit=true(raw client) commits offsets on a timer duringpoll(), independent of whether processing finished. A commit before completion can lose records, and a crash after processing but before the next commit causes duplicates.- Spring Kafka disables auto-commit by default and lets the container commit. The default
AckMode.BATCHcommits after a poll's records are handled.MANUAL_IMMEDIATEcommits when you callack.acknowledge(), so acknowledge only after the DB transaction and the async enrichment have both completed.
Why rebalances duplicate work. Committed offsets always trail completed work. If a partition is revoked after the DB write but before the offset commit (crash, deploy, or exceeding max.poll.interval.ms due to slow enrichment), the next owner resumes from the last committed offset and reprocesses. This is at-least-once delivery behaving as designed. Producer idempotence only removes duplicates from producer retries, not from consumer redelivery.
Idempotent design.
- Use a stable business key from the event, such as
authorizationId. Do not use partition/offset, which changes if a message is republished. - Enforce uniqueness in the database, in the same transaction as the ledger write:
CREATE TABLE processed_event (
consumer_group TEXT, event_id UUID,
processed_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (consumer_group, event_id));
ALTER TABLE ledger_entry
ADD CONSTRAINT uq_ledger UNIQUE (authorization_id, entry_type);
@Transactional
public void post(PaymentAuthorized e) {
int n = jdbc.update("""
INSERT INTO processed_event(consumer_group, event_id)
VALUES (?, ?) ON CONFLICT DO NOTHING""", GROUP, e.authorizationId());
if (n == 0) return; // duplicate: skip, but still ack
ledgerRepo.insertDebit(e);
}
- Optionally add a state guard such as
UPDATE payment SET status='POSTED' WHERE id=? AND status='AUTHORIZED'; zero updated rows means it was already handled.
Two instances racing on the same record serialize on the primary key, so exactly one wins. The loser skips and acknowledges.
Poison pills.
- Wrap deserializers in
ErrorHandlingDeserializerso corrupt bytes become a handled error instead of a re-poll loop. - Mark non-retryable exceptions (validation, deserialization) so they skip retries; use bounded backoff for transient ones.
- After retries, publish the record to a dead-letter topic (
payment-authorizations.DLT) with failure headers, commit its offset, and alert on DLT depth.
C. Concurrency and the dual-write problem
Why HashMap fails. Concurrent resizes can drop entries, put(k, get(k)+1) loses updates, and iterating during mutation throws ConcurrentModificationException.
| Option | Reads | Writes | Notes |
|---|---|---|---|
synchronizedMap | one global mutex | one global mutex | Simple, but serializes everything; iteration must be manually synchronized. |
ReentrantLock / RW lock | exclusive, or shared with RW | exclusive | Good for multi-key invariants and tryLock timeouts; RW locks add overhead and can starve writers. |
ConcurrentHashMap | lock-free | CAS on empty bins, per-bin lock otherwise | Weakly consistent iterators (no CME), atomic compute/merge. |
For read-heavy metrics, pick ConcurrentHashMap with LongAdder values, or simply use Micrometer counters:
counts.computeIfAbsent(key, k -> new LongAdder()).increment();
Memory "leaks" in such caches usually come from unbounded key cardinality (for example per-transaction-ID keys). Use low-cardinality keys, or bound and expire entries.
DB commit succeeds, offset commit fails. The record is redelivered and processed again. Because of the idempotency design above, the second attempt hits the unique key, does nothing, and acknowledges. You cannot make a DB commit and a Kafka offset commit atomic across two systems, so the answer is "make redelivery harmless", not "prevent it".
Other dual-write cases.
- If the service must also publish an event after its DB write, use a transactional outbox: insert the outgoing event into an
outboxtable in the same DB transaction, and have a relay (poller or CDC such as Debezium) publish it. Consumers downstream remain idempotent. - For pure Kafka-to-Kafka flows, use Kafka transactions with
sendOffsetsToTransaction, so output records and offsets commit atomically. - Alternatively, store offsets in the database with the business write and seek to them on assignment. This is stronger but more operationally involved.
Common mistakes
- Using
MODE_INHERITABLETHREADLOCALand assuming it is fine with pools. - Deduplicating in an in-memory set, which is lost on restart and not shared across instances.
- Acknowledging before the DB commit, or not acknowledging duplicates, which causes endless redelivery.
- Retrying poison records forever, blocking the partition.
- Claiming Kafka producer idempotence gives end-to-end exactly-once.