Java + Python System Design Implementation Cookbook
This cookbook turns high-level architecture claims into executable patterns. Each pattern states its invariant, the language-specific mechanism, and the distributed-systems caveat.
- 1. Idempotent write
- 2. Optimistic concurrency
- 3. Pessimistic inventory/seat lock
- 4. Cache-aside + stampede control
- 5. Atomic Redis rate limiter
This cookbook turns high-level architecture claims into executable patterns. Each pattern states its invariant, the language-specific mechanism, and the distributed-systems caveat.
1. Idempotent write
Invariant: the same logical client retry must not create a second business effect.
Java / Spring Boot
1@Transactional2public PaymentResponse create(String key, PaymentRequest req) {3 var found = idemRepo.find("payment", key);4 if (found.isPresent()) {5 if (!found.get().requestHash().equals(hash(req))) throw new ConflictException();6 return decode(found.get().response());7 }8 Payment p = payments.save(Payment.pending(req.amount()));9 PaymentResponse out = PaymentResponse.from(p);10 idemRepo.save(new IdempotencyRecord("payment", key, hash(req), encode(out)));11 outbox.save(OutboxEvent.of("PaymentCreated", p.getId(), encode(out)));12 return out;13}Back scope,key with a unique database constraint and handle the concurrent-insert race by loading/replaying the winner.
Python / SQLAlchemy
1async def create_payment(session, key, req):2 try:3 async with session.begin():4 old = await session.scalar(select(Idem).where(Idem.scope=="payment", Idem.key==key))5 if old:6 if old.request_hash != hash_req(req): raise Conflict()7 return old.response8 p = Payment(amount=req.amount, status="PENDING")9 session.add(p); await session.flush()10 out = serialize(p)11 session.add(Idem(scope="payment", key=key, request_hash=hash_req(req), response=out))12 session.add(Outbox(kind="PaymentCreated", aggregate_id=str(p.id), payload=out))13 return out14 except IntegrityError:15 await session.rollback()16 return await replay_existing(session, "payment", key, req)2. Optimistic concurrency
Java
1@Entity class InventoryItem {2 @Id Long id;3 @Version long version;4 int available;5}Update in one transaction and retry boundedly on an optimistic-lock conflict only if the operation is safe to retry.
Python
1stmt = (update(Inventory)2 .where(Inventory.id == item_id, Inventory.version == expected_version,3 Inventory.available >= qty)4 .values(available=Inventory.available-qty,5 version=Inventory.version+1))6result = await session.execute(stmt)7if result.rowcount != 1: raise Conflict()3. Pessimistic inventory/seat lock
Java
1@Lock(LockModeType.PESSIMISTIC_WRITE)2@Query("select s from Seat s where s.id=:id")3Seat lockSeat(@Param("id") Long id);Python
1seat = await session.scalar(2 select(Seat).where(Seat.id == sid).with_for_update()3)Keep the transaction short. Never hold the DB lock while waiting on a slow payment provider.
4. Cache-aside + stampede control
Java pseudocode
1Value get(String k) {2 var v = redis.get(k); if (v != null) return v;3 if (redis.setNx("fill:"+k, token, Duration.ofSeconds(2))) {4 try { v = repo.load(k); redis.set(k, v, ttlWithJitter()); return v; }5 finally { compareAndDelete("fill:"+k, token); }6 }7 return staleCacheOrBoundedRetry(k);8}Python pseudocode
1async def get_item(k):2 if v := await redis.get(k): return decode(v)3 token = uuid.uuid4().hex4 if await redis.set(f"fill:{k}", token, nx=True, px=2000):5 try:6 v = await repo.load(k)7 await redis.set(k, encode(v), ex=ttl_with_jitter())8 return v9 finally:10 await compare_delete(redis, f"fill:{k}", token)11 return await stale_or_short_wait(k)For strict correctness, cache remains an optimization; source-of-truth validation happens in the database/service that owns the invariant.
5. Atomic Redis rate limiter
Prefer one server-side script/function so refill + consume is one atomic transition. Key by the actual policy scope. Return allowed, remaining, and retry-after. Use server time to avoid client clock skew. Decide fail-open/fail-closed per endpoint.
6. Consistent hashing
Use a stable 64-bit+ hash and many virtual nodes. On node add/remove, move only affected ranges. Track replication separately: map a key to the first N distinct physical nodes clockwise or use rendezvous hashing. Consistent hashing does not solve membership consensus or hot keys.
7. Transactional outbox publisher
SQL claim pattern
1SELECT id, aggregate_id, sequence, payload2FROM outbox3WHERE published_at IS NULL4ORDER BY id5FOR UPDATE SKIP LOCKED6LIMIT 100;Publish with stable event_id; after broker ack mark published. Crash after ack can republish; consumer inbox/idempotency is still required. Preserve aggregate ordering by sequence/partition key.
8. Idempotent Kafka consumer
Java shape
1@Transactional2public void handle(Event e) {3 if (!processed.tryInsert(e.id())) return;4 domain.apply(e);5}Python shape
1async with session.begin():2 inserted = await insert_processed_if_absent(session, event.id)3 if not inserted: return4 await apply_domain_change(session, event)The processed marker and domain effect must share the same local transaction to close the crash window.
9. Bounded fan-out
Java
1ExecutorService pool = Executors.newFixedThreadPool(32);2var a = CompletableFuture.supplyAsync(() -> clientA.get(id), pool);3var b = CompletableFuture.supplyAsync(() -> clientB.get(id), pool);4return a.thenCombine(b, View::new).orTimeout(250, TimeUnit.MILLISECONDS).join();Python
1sem = asyncio.Semaphore(32)2async def bounded(coro):3 async with sem:4 return await asyncio.wait_for(coro, timeout=.25)5a,b = await asyncio.gather(bounded(client_a.get(id)), bounded(client_b.get(id)))Bounded concurrency protects dependencies and your own memory/queues.
10. Retry with jitter
Pseudocode: wait min(cap, base 2^attempt) random(0.5,1.5). Retry only errors classified transient, only idempotent/safe operations, and only while the total request deadline leaves enough time. Emit retry metrics by dependency/error type.
11. Circuit breaker
Maintain rolling error/slow-call statistics. Open after threshold/minimum volume; reject immediately. After cooldown allow a small number of probes. Keep breakers per dependency/operation where failure behavior differs. A breaker is not a substitute for timeout or bulkhead.
12. Lease + fencing token
A lock service grants (resource, token=42, expiry). New owner later receives token 43. Every write to the protected resource carries token; resource stores highest accepted token and rejects <43. This prevents a paused old owner from corrupting state after lease expiry.
13. Saga orchestration
Persist saga row/state before/with each step transition. Commands include stable saga/step IDs. Each participant is idempotent. On terminal failure, issue compensations in business-defined order; compensation failures are retried/reconciled rather than pretending a global rollback exists.
14. Cursor pagination
Use stable ordered tuple (created_at,id). Encode it opaquely to clients. Always include deterministic unique tie-breaker. For descending pagination:
1SELECT ... FROM post2WHERE tenant_id=? AND (created_at,id) < (?,?)3ORDER BY created_at DESC,id DESC4LIMIT 51;Return 50 plus a next cursor if row 51 exists.
15. Health + graceful shutdown
Readiness should fail before shutdown so load balancer stops new traffic. Drain in-flight HTTP/WebSocket work, stop consuming new broker records, finish/abort bounded work, commit safe offsets, and close pools. Liveness should detect wedged process without depending on every optional downstream service.
16. What to test
- concurrency tests for duplicate idempotency keys and seat/inventory conflicts;
- crash between DB commit and event publish (outbox recovers);
- crash after event effect before offset commit (consumer dedupe works);
- cache unavailable/hot-key stampede;
- dependency timeout + retry storm;
- queue/Kafka lag and poison record;
- primary DB failover and stale replica read;
- lease expiry while old worker is paused;
- load test at saturation to verify bounded queues/load shedding;
- trace propagation across HTTP and event boundaries.
Mastery check
How well can you recall this?
Finished this lesson?