How the software was designed: the low-level design and the reasoning behind it
Low-level design (LLD) is the level of classes, interfaces, responsibilities, data shapes and interactions. This module explains how the three projects were designed: the process (spec first, build in ordered steps), the forces that shaped the classes, the principles and patterns applied (with the exact classes), the key interaction diagrams, and how to use the same thinking in an LLD interview round.
By the end you can answer
- "How did you go about designing this? Walk me through your class design."
- "Why is the code organised this way? Why these modules and packages?"
- "Which design patterns did you use, and why there?"
- "How did you make it testable?"
- "Show me SOLID in your code."
- "Design a leaderboard / a moderation state machine / an agent loop / a retry library." (an LLD round)
1. HLD vs LLD in one minute
| High-level design (HLD) | Low-level design (LLD) | |
|---|---|---|
| Unit | Services, data stores, queues, networks | Classes, interfaces, methods, data records |
| Questions | What talks to what? Where does data live? How does it scale? | Who owns which responsibility? What are the seams? How do objects collaborate? |
| In this guide | Modules 01 and 18 | This module and the atlases (19–21) |
2. The design process: specification first, then ordered steps
Each project began as a detailed implementation specification (Arena 1,441 lines, Telemetry 1,309, Judge 1,187) before any code. All three specs share the same anatomy. That shared skeleton is a design method, and you can describe it in an interview:
| Spec section | What it decides | Why it comes early |
|---|---|---|
| Overview, goals, non-goals | Who calls it, what it must do, what it must not (no frontend, no Kafka in Arena, no rate limiting...) | Non-goals stop scope creep and keep the design small |
| Rules | Records for DTOs, constructor injection, an injected Clock, UTC Instants, Java-generated UUIDs, ProblemDetail errors, no hard-coded secrets, "simplest option + a DECISION comment where the spec is silent" | Cross-cutting conventions decided once, not per class |
| Tech stack and pitfalls | Exact versions; a table of APIs that changed in Boot 4, Jackson 3, Kafka 4 | New versions break most online examples |
| Project structure | Packages or modules and every planned file | The skeleton of the LLD |
| Configuration | Every setting, default and validation rule | Behaviour that changes without code |
| Contracts (schema, endpoints, topics, JSON fields, error codes) | Everything another service depends on | Three services must agree; contracts are frozen |
| Domain sections | The state machine, leaderboard, topology, agent, routing and policy tables | The real logic, stated as rules and tables |
| Observability, testing, delivery | Metric names, test layers, coverage gates, Docker, CI | Quality designed in, not bolted on |
| "How each number is measured" | The method for every résumé claim | Prevents vague or unverifiable claims |
| Build order + acceptance checklist | 12 steps, each ending with ./mvnw verify green; final checks (grep for forbidden APIs, coverage, measured README) | Always-working increments; a definition of done |
The build orders (each step had to pass before the next)
| Step | Arena | Telemetry | Judge |
|---|---|---|---|
| 1 | Bootstrap | Skeleton (parent POM, 4 modules, broker only) | Skeleton + settings records |
| 2 | Configuration and schema (app starts with validate) | Common: contracts, serde, test helpers | SDK smoke test (compiles; live run pending) |
| 3 | Error foundation | Simulator core (no Kafka) | Verdict schema, parser, validator |
| 4 | Security and auth | Topology: parse and DLT | Prompts and tools (guard, memoising) |
| 5 | Players | Topology: integrity | The agent loop |
| 6 | Leaderboard | Topology: detection (windows, join, cooldown) | Resilience and cost |
| 7 | Matches (locking, idempotency) | Detector app (Spring wiring, health, ITs) | Routing and policy, JudgeEngine |
| 8 | Moderation (state machine, guardrails) | Simulator app (engine, publisher, manifest) | Service, Arena side |
| 9 | Appeals | Verifier | Service, Kafka side |
| 10 | Observability | Observability and delivery | Fault injection (ResilienceIT) |
| 11 | Delivery (Docker, CI) | Arena integration | Evaluation harness |
| 12 | Benchmark and README | Measure and document | Deliver (Docker, CI, dashboard, README) |
The ordering principle: foundation before features, pure logic before infrastructure, features in dependency order, measurement last. Errors and security come before any feature, so every feature is born with the right error format and access rules. In the Judge and Telemetry, the pure core (verdict pipeline, topology) was built and tested before any Spring or Kafka wiring.
The specs include a "Rules for the coding agent" section, so they were written to direct an AI coding assistant. That is a legitimate and increasingly common way to build. The design work is in the spec: the contracts, the rules, the tables, the build order and the acceptance tests. The judgement shows in the deviations, where the spec was wrong and the implementation chose differently, with a documented reason (module 16). Describe it truthfully (module 15, section 6), and make sure you can defend every class. That's what this module and the atlases are for.
3. The forces that shaped the classes
Good LLD is a response to forces. These were the main ones, and each left a visible mark on the code:
| Force | Design response | Where |
|---|---|---|
| "Never ban an innocent player" | Layered guardrails; the model can't act; pure policy | DecisionPolicy, GuardedToolExecutor, ModerationService.enforceGuardrails, the DB trigger |
| Three services must agree | Explicit contract types per service (copies, not a shared jar); frozen names | SuspiciousPlayer in both P2 and P3; MatchSummary shaped like Arena's request |
| At-least-once delivery between services | Idempotency keys, dedup stores, state checks | externalId, ProcessedFlags, PreChecks |
| Correctness must be provable | Pure, exhaustively testable classes; measurement built into the design | AccountStateMachine, IntegrityProcessor + IntegrityChecker, Scorer |
| Nondeterminism (time, randomness, LLMs) | Inject Clock; seeded generators; an LLM gateway interface | ClockConfig everywhere; SplittableRandom(seed + k); MessagesGateway |
| External systems fail | Classify failures into types; hold vs dead-letter | RetryableArenaException/NonRetryable...; LlmUnavailableException/NonRetryableJudgeException |
| Evaluation must measure production behaviour | One engine for both apps; recorded tools behind the same interface | JudgeEngine, ToolExecutor, RecordedToolExecutor |
| Cost (tokens, broker traffic) | Routing, caching, memoised tools; no unplanned repartitions | ModelRouter, PromptLibrary, MemoizingToolExecutor, the mapValues re-parse |
4. Design principles, with the classes that embody them
4.1 Functional core, imperative shell
Put decisions in pure code (no I/O, no framework, same input gives same output) and keep I/O at the edges. Pure code is trivially testable, easy to reason about and safe to reuse.
| Pure core | Imperative shell around it |
|---|---|
AccountStateMachine, RatingCalculator | ModerationService, AppealService, MatchService (transactions, events, metrics) |
DetectionRules, AimStats, SpeedStats, EventParser, TelemetryTopology | StreamsWiring, the Kafka Streams runtime |
DetectionEvaluator, IntegrityChecker | VerifierRunner, TopicSnapshotReader, ReportWriter |
DecisionPolicy, EscalationRule, CostCalculator, VerdictParser/Validator, Scorer, CaseSampler | JudgeService, FlagListener, EvalCli |
4.2 Ports and adapters (hexagonal architecture)
The core defines ports (interfaces it needs); the outside world plugs in adapters. The core never imports a framework, and tests plug in fakes.
┌──────────────── judge-core (no Spring, no Kafka) ────────────────┐
Claude API ◄── ResilientMessagesGateway ──implements──► MessagesGateway (port) ◄── AgentLoop
(adapter) ▲
ScriptedGateway (test fake) ─────────────implements───────────────────┘
Arena HTTP ◄── ArenaClient (service) ─┐
Arena HTTP ◄── ArenaHttpReader (eval) ┴─implements─► ArenaReader (port) ◄── ArenaToolExecutor
│
snapshots ──► RecordedToolExecutor ──implements──► ToolExecutor (port) ◄── AgentLoop (via guard)
FakeToolExecutor (test) ───┘
└──────────────────────────────────────────────────────────────────┘
Other ports: TopologyMetrics (Micrometer adapter in the app, NOOP and test counters elsewhere), TopicSource (Kafka adapter vs in-memory for collect tests), and java.time.Clock (system UTC vs fixed or mutable).
4.3 Make illegal states unrepresentable
- Records validate in compact constructors, so invalid settings, dead letters or verdict collections can't exist (
DetectionProperties,JudgeSettings,DeadLettercaps its error,Investigationrequires an attempt). - Sealed types for outcomes:
ParseResultis eitherParsedorFailed, nothing else. - Enums plus a transition table instead of free-form status strings:
AccountStateMachine. - Defensive copies (
List.copyOf) in records likeArenaActionandVerdict, so callers can't mutate them later.
4.4 Errors as values, and classified exceptions
Expected failures are data, not crashes: ParseResult.Failed → a dead letter; ToolResult.error → returned to the model; DeadLetter records. Unexpected or external failures become a small set of meaningful exception types that drive behaviour: retryable vs non-retryable (bridge), unavailable vs non-retryable (Judge), ApiException(ErrorCode) (Arena). The type is the decision.
4.5 Explicit over implicit
TransactionTemplate instead of a hidden proxy where the boundary matters; a named repartition; topics declared in code with auto-create off; the decorator order spelled out in ResilientMessagesGateway; the policy as a numbered table; @Import for the shared config.
4.6 Fail fast, and determinism
Every service validates configuration and secrets at startup and names what's wrong. Every source of nondeterminism is injectable: time (Clock), randomness (seeds per shard), the LLM (gateway), the network (adapters).
4.7 Boundaries that the compiler enforces
- Package-by-feature (Arena):
auth,player,match,leaderboard,moderation,appeal, each with its own controller, service, repository and DTOs. A change to appeals touches one package. Contrast with package-by-layer (controllers/,services/...), where every feature is spread across all of them. - Maven modules (Telemetry, Judge):
judge-corecan't import Spring because it isn't on its classpath; apps can't depend on each other; shared contracts live intelemetry-common. - Visibility: package-private Spring classes (
StreamsWiring,MicrometerTopologyMetrics) and package-private helpers exposed only to tests in the same package.
5. SOLID, shown in your code
| Principle | Meaning | Example |
|---|---|---|
| Single responsibility | One reason to change | Telemetry's processors each do one job (parse, integrity, cooldown); in the Judge, AgentLoop talks to the model, ModelRouter picks the model, DecisionPolicy picks the action, ArenaActionApplier sends it |
| Open/closed | Extend without modifying | New tool backends implement ToolExecutor; new wrappers (logging, metrics) can decorate it without touching AgentLoop; a new prompt version is a new folder |
| Liskov substitution | Implementations are interchangeable | Any ToolExecutor (live, recorded, fake) or MessagesGateway (resilient, scripted) works in the loop unchanged; that's what makes evaluation and tests possible |
| Interface segregation | Small, focused interfaces | MessagesGateway has one method; ArenaReader has three reads (actions are a separate concern on ArenaClient); TopicSource has one |
| Dependency inversion | Depend on abstractions; the core owns the interfaces | judge-core defines ArenaReader and MessagesGateway; the service and eval provide implementations |
6. Design patterns, and exactly where they are
| Pattern | What it solves | Your classes |
|---|---|---|
| Layered architecture | Separate HTTP, business rules and persistence | Arena: *Controller → *Service → *Repository |
| Repository / query object | Hide data access behind a collection-like interface | Spring Data repositories; ModerationQueueQuery (a hand-written SQL query object) |
| DTO + mapper | Decouple the wire format from entities | Records in dto/; PlayerMapper (MapStruct); ArenaToolExecutor maps Arena JSON to compact tool JSON |
| State machine (table-driven) | Legal transitions in one place | AccountStateMachine; client-side mirror in PlayerStatus.canBeFlagged() |
| Decorator | Add behaviour by wrapping the same interface | GuardedToolExecutor(MemoizingToolExecutor(ArenaToolExecutor)); Resilience4j's decorateSupplier chain |
| Adapter | Fit an external API to your interface | ResilientMessagesGateway (SDK → MessagesGateway), ArenaClient and ArenaHttpReader (HTTP → ArenaReader), KafkaTopicSource, MicrometerTopologyMetrics |
| Strategy | Swap an algorithm or behaviour | EvalMode (routed, baseline, haiku-only change the settings); tool backends; metrics implementations |
| Facade | One simple entry point to a subsystem | JudgeEngine.judge(); TelemetryTopology.addTo() |
| Chain of responsibility / first-match rules | Ordered checks where the first match wins | DecisionPolicy rows; EscalationRule reasons; the servlet filter chain |
| Observer / publish-subscribe | Decouple producers from reactions | Spring events (RatingChanged → LeaderboardSync); Kafka topics between services |
| Template method | Override steps of a base algorithm | GlobalExceptionHandler overrides hooks of ResponseEntityExceptionHandler |
| Static factory methods | Named constructors with intent | Evidence.aimbot(), FlagCandidate.speedhack(), ToolResult.ok()/error(), VerdictRecords.skipped(), PageResponse.from(), JudgeEngine.create(), JsonSerdes.of() |
| Builder | Readable construction of complex objects | SDK MessageCreateParams.builder(), TopicBuilder, Timer.builder(), Resilience4j configs |
| Null object | Avoid null checks with a harmless default | TopologyMetrics.NOOP, AgentStats.EMPTY, TokenUsage.ZERO, IntegrityStats.empty() |
| Command | Requests as objects | Eval commands (collect/run/compare); verifier modes; moderation actions recorded as rows |
| Snapshot + atomic swap | Lock-free reads of rebuilt data | StatDistributionService (AtomicReference); LeaderboardRebuilder (RENAME) |
| Memoisation | Compute once per key | MemoizingToolExecutor |
| Value object | Equality by value, immutable | MatchParticipantId, TokenUsage, Evidence, AimStats |
| Event sourcing (light) | Rebuild state by replaying a log | ProcessedFlagsLoader replaying judge-verdicts; KTables from compacted topics |
| Idempotent receiver | Make duplicate messages harmless | externalId; FlagListener + ProcessedFlags |
| Dead letter channel | Park unprocessable messages | match-events.DLT, match-summaries.DLT, suspicious-players.judge.DLT |
| Circuit breaker, retry, rate limiter | Stability around remote calls | AnthropicResilience, the Judge's ArenaClient, the bridge's error handler |
7. Key interactions as sequence diagrams
Arena: POST /matches
Bridge MatchController MatchService PlayerRepository / DB LeaderboardSync Redis
│ POST /matches │ │ │ │ │
│───────────────►│ @Valid, role │ │ │ │
│ │────────────────►│ recordTx.execute { │ │ │
│ │ │ validate; findByExternalId ─────────────────────────►│ │
│ │ │ sort ids; findAllByIdInForUpdate (ORDER BY id) ─────►│ row locks │
│ │ │ saveAndFlush(match); RatingCalculator per player │ │
│ │ │ setters on managed Players; saveAll(participants) │ │
│ │ │ publishEvent(RatingChanged) ──(held) │ │
│ │ │ } commit ───────────────────────────────────────────►│ COMMIT │
│ │ │ │──── AFTER_COMMIT ─────────►│ ZADD ──────►│
│ │◄────────────────│ RecordResult(created) │ │ │
│◄─── 201 + Location (or 200 replay; a unique-violation race is caught after rollback → 200)
Telemetry: the simulator's object graph
SimulationEngine (thread "simulation-main")
├─ PopulationFactory ── CheaterAssignment, BehaviorProfile ──► List<PlayerState>
├─ ArenaPlayerRegistrar (optional) ── ArenaClient (virtual threads + Semaphore)
├─ EventPublisher ── KafkaTemplate<String, byte[]> ──► ManifestTracker (acks / failures)
└─ per shard k: ScheduledExecutor ─ ShardWorker(k)
├─ SplittableRandom(seed + k), MalformedInjector
├─ MatchRoom × n ──(round ends)──► MatchSummaryBuilder ──► EventPublisher
└─ EventFactory.tick(player) ──► sink: publish(event) [+ maybe malformed]
Telemetry: the verifier pipeline
VerifierRunner (--mode)
├─ detection: TopicSnapshotReader(ground truth, flags, profiles) ─► DetectionEvaluator (pure)
│ ─► ReportWriter.renderDetection ─► exit 0 or 2
└─ integrity: TopicSnapshotReader(manifest, integrity-stats) ─► IntegrityChecker (pure)
─► (settle loop) ─► ReportWriter.renderIntegrity ─► exit 0 or 1 [3 = not finished, 4 = bad args]
Judge: one flag
FlagListener ─► parse ─► ProcessedFlags.hasFlag? ─yes─► skip (idempotent)
│no
▼
JudgeService ─► ArenaClient.player ─► PreChecks (+ recentlyJudged) ─skip─► VerdictRecords.skipped
│judge
▼
JudgeEngine.judge(flag, ArenaToolExecutor(player))
└─ ModelRouter
├─ AgentLoop(haiku) ─► ResilientMessagesGateway ─► Claude
│ └─ tools: Guarded ─► Memoizing ─► ArenaToolExecutor ─► ArenaReader
├─ EscalationRule ─(escalate)─► AgentLoop(sonnet, fresh conversation, same Memoizing)
└─ Investigation (verdict + attempts with cost)
└─ DecisionPolicy.decide(verdict, status) ─► ArenaAction
ArenaActionApplier ─► ArenaClient.applyAction ─(409)─► re-read status ─► decide again ─► send
VerdictRecords.judged ─► JudgeMetrics ─► FlagListener: VerdictPublisher.publish(...).join() ─► remember
8. Data design: records as the vocabulary
Each project's data model is a small, deliberate vocabulary of immutable records:
- Arena: entities only for persisted aggregates (
Player,Match,MatchParticipant,ModerationAction,Appeal,RefreshToken); everything crossing HTTP is a record; domain events are records. - Telemetry: every event, contract, store value and report is a record (
MatchEvent,SuspiciousPlayer,AimStats,IntegrityStats,DetectionReport...). The one mutable class,MatchRoom.PlayerTotals, is a deliberate, documented exception: a thread-confined accumulator. - Judge: a pipeline of records, each a stage's output:
SuspiciousPlayer→Verdict→Attempt→Investigation→ArenaAction→JudgeOutcome→JudgeVerdictRecord. Reading the types tells you the algorithm.
"I model each stage's output as an immutable record, so the types tell the story of the pipeline: a flag becomes a verdict, attempts become an investigation, and the investigation becomes exactly one action. Each stage is a pure function I can test on its own."
9. Designing for testability: the seams
| Seam | Production | Test double | What it unlocks |
|---|---|---|---|
Clock | Clock.systemUTC() | Fixed / MutableClock | Expiry, cooldowns, windows, punctuators, latency |
MessagesGateway | Resilient SDK gateway | ScriptedGateway | The whole agent without network or money |
ToolExecutor | ArenaToolExecutor | FakeToolExecutor, RecordedToolExecutor | Tool behaviour and the evaluation |
TopologyMetrics | Micrometer | Counters / NOOP | Assert metric calls in topology tests |
TopicSource | Kafka | In-memory records | collect without a broker |
StreamsBuilder | Spring Kafka's | TopologyTestDriver | The full topology at exact timestamps |
| Base URLs from configuration | Real Arena and Claude | WireMock container, StubArenaServer | HTTP faults and contracts |
| Package-private constructors | Spring's constructor | Test constructor (with a clock) | Control without reflection |
10. Using this in an LLD interview round
A reliable method for any "design the classes for X" question:
- Clarify the use cases and constraints (scale, consistency, who calls it).
- Find the nouns and the states: entities, value objects, statuses and their transitions.
- Put the rules in pure classes (a state machine, a policy, a calculator).
- Define ports for everything external (storage, clock, network, model).
- Choose patterns deliberately (decorator for cross-cutting behaviour, strategy for variants).
- Walk one sequence end to end, including the failure path.
- Say how you'd test it.
Practice prompts answered from your own code
Design a game leaderboard service
interface RankStore { void upsert(id, score); void remove(id); Optional<Long> rank(id); List<Entry> page(offset, limit); long size(); }
class RedisRankStore implements RankStore // ZADD / ZREM / ZREVRANK / ZREVRANGE / ZCARD
class LeaderboardService { RankStore store; PlayerRepository players; Clock clock; ... }
record RatingChanged(UUID playerId, int rating) // published in the write transaction
class LeaderboardSync { @TransactionalEventListener(AFTER_COMMIT) onRatingChanged(...) }
class LeaderboardRebuilder { rebuild(): keyset-stream truth → temp key → atomic swap }
final class RatingCalculator { static int delta(n, placement, maxDelta) } // pure
Talking points: truth vs derived index, after-commit sync, tie-breaking identical in both stores, rebuild by atomic swap, and the outbox as the upgrade.
Design account moderation with appeals
enum Status { ACTIVE, FLAGGED, BANNED, APPEALED, REINSTATED }
enum Action { FLAG, BAN, CLEAR, NOTE, APPEAL_SUBMITTED, APPEAL_UPHELD, APPEAL_OVERTURNED }
final class StateMachine { Status next(Status current, Action action) } // EnumMap tables; throws on illegal
record ModerationAction(id, player, action, from, to, actor, source, reason, evidence, confidence, review, at) // append-only
class ModerationService { apply(target, request, actor): guardrails → stateMachine.next → save audit row → events }
class AppealService { submit(...), decide(...) } // the same state machine and audit table
Talking points: one transition contract, append-only audit (with a trigger), guardrails per actor type, optimistic locking for concurrent moderators.
Design an LLM agent that takes actions safely
interface ModelGateway { Response create(Request r); } // adapter: retries, breaker, limiter
interface ToolExecutor { ToolResult execute(String tool, Json input, Scope scope); }
class GuardedTools implements ToolExecutor // allow-list, schema, scope (only the flagged player)
class MemoizedTools implements ToolExecutor // per-task cache
class AgentLoop { Run run(model, task, tools) } // bounded turns and tool calls; strict output parsing
class Router { Investigation investigate(task) } // cheap model → escalate → strong model, fresh context
final class Policy { Action decide(Verdict v, State s) } // pure: the only place actions are chosen
class Applier { Applied apply(Action a) } // executes; handles conflicts by re-deciding
Talking points: the model never chooses actions; bounded loops; schema plus validator; injection containment; evaluation through the same engine.
Design a retry + circuit-breaker utility
A Retry (max attempts, an IntervalFunction with exponential jittered backoff, a retryOn(Throwable) predicate, Retry-After support), a CircuitBreaker (count-based ring buffer, a failure-rate threshold with a minimum number of calls, CLOSED/OPEN/HALF_OPEN states with an open-state timer and limited trial calls, a recordOn/ignoreOn classification), and a RateLimiter (permits per period and an acquire timeout), all as Supplier decorators composed Retry(Breaker(Limiter(call))). Mention why the order matters and why the breaker ignores 4xx and 429 (module 12).
Design an event de-duplicator for a noisy detector
A keyed store (entityId|ruleId) → lastEmittedAt, a Clock, and a cooldown Duration; drop when now − last < cooldown, else store and emit. Key by rule so one rule never hides another. Discuss the choice of event time vs wall time, store growth (TTL or windowed stores), and placement after the repartition so all of an entity's candidates hit the same store (that's CooldownProcessor).
11. Interview questions
How did you approach the design of these projects? Basic
Specification first: goals and non-goals, conventions, the stack and its pitfalls, structure, configuration, every contract other services depend on, the domain rules as tables, testing and delivery, how each claimed number would be measured, and a 12-step build order where every step must pass the full build before the next. Then I built in that order: foundations, errors and security first, pure logic before infrastructure, measurement last, and documented every deviation where the spec turned out wrong.
Why package-by-feature in Arena? Basic
Cohesion and change locality: everything about appeals (entity, repository, service, controller, DTOs) lives together, so a change to appeals touches one package. Package-by-layer spreads each feature across every layer folder and encourages services to reach into each other's repositories. Package-by-feature also makes it obvious where a future split into separate services would cut.
Which pattern are you proudest of, and why? Intermediate
The decorator chain of tool executors in the Judge: GuardedToolExecutor wrapping MemoizingToolExecutor wrapping a backend that's either live Arena or recorded snapshots. Safety, caching and data source are three independent concerns composed through one interface, so the evaluation runs exactly the production safety rules on recorded data, and tests swap in a fake. The agent loop doesn't know any of it exists.
Show me dependency inversion in your code. Intermediate
judge-core owns the interfaces it needs (MessagesGateway, ToolExecutor, ArenaReader) and has no Spring, Kafka or HTTP client on its classpath. The service implements them with a resilient SDK gateway and a RestClient-based Arena client; the evaluation implements them with recorded snapshots and a small HTTP reader; tests use scripted fakes. High-level policy doesn't depend on low-level details; both depend on abstractions the core defines.
Why did you copy contract types into each service instead of sharing a jar? Deep
The contract is the JSON on the topic or the HTTP API, not a Java class. A shared jar would couple the services' release cycles and build tooling. Separate repositories should be independently deployable. Each service models what it consumes (the Judge's SuspiciousPlayer ignores unknown fields), which allows the producer to add fields safely. The risk, silent renames, is what a schema registry with compatibility rules solves at scale.
How did you design for testability? Intermediate
By putting every source of nondeterminism or I/O behind a seam: an injected Clock, seeded randomness, a model gateway interface, a tool executor interface, a metrics interface, a topic source, configurable base URLs. The core logic is pure. The result: exhaustive unit tests (35 state pairs, every policy row), whole-topology tests at exact timestamps, a whole agent tested without network, and real-infrastructure tests only where they add value.
Where would your design not hold up, and what would you refactor? Deep
Arena's in-memory domain events to Redis (I'd introduce an outbox table and a relay); the Judge's in-memory ProcessedFlags (a TTL store or windowed eviction); the integrity processor re-emitting every player every 5 seconds (emit only changed players, or sample, at large scale); MatchService doing a lot in one method (I'd extract a "match recording" domain object). And where the code mirrors another service's rules (PlayerStatus.canBeFlagged mirrors Arena's state machine), I'd want contract tests so the two can't drift.
Why is MatchRoom.PlayerTotals a mutable class when everything else is a record? Curveball
Because it isn't data in flight: it's a thread-confined accumulator incremented thousands of times a second inside one shard thread. Allocating a new record per increment would be pure garbage. The rule is "records for values that cross boundaries (events, DTOs, stored state)"; a private accumulator that never escapes its thread is the documented exception.
12. Quick quiz
1. GuardedToolExecutor wrapping MemoizingToolExecutor is an example of:
Same interface, added behaviour, composable.
2. ResilientMessagesGateway implementing MessagesGateway over the SDK is primarily:
It adapts an external API to the port the core defines (and decorates it with resilience).
3. "Functional core, imperative shell" means:
Example: DecisionPolicy (pure) inside JudgeService (I/O).
4. In the build orders, what came before any feature?
So every feature is born with the right errors and access rules.
5. TopologyMetrics.NOOP is an example of:
A harmless default implementation instead of null checks.
13. Cheat sheet
- Process: spec (goals and non-goals, rules, pitfalls, structure, config, contracts, domain tables, testing, delivery, measurement method, 12-step build order) → build in order, every step green → document deviations.
- Order: foundation → errors and security → features by dependency → observability → delivery → measurement.
- Principles: functional core; ports and adapters; illegal states unrepresentable; errors as values plus classified exceptions; explicit over implicit; fail fast; determinism; compiler-enforced boundaries.
- SOLID: processors, loop/router/policy/applier (S); new executors and prompt folders (O); interchangeable executors and gateways (L); tiny ports (I); core-owned interfaces (D).
- Patterns: layered, repository, DTO + mapper, state machine, decorator, adapter, strategy, facade, first-match rules, observer, template method, factories, builder, null object, command, snapshot swap, memoisation, value object, event sourcing (light), idempotent receiver, dead letter channel, resilience patterns.
- Seams: Clock, MessagesGateway, ToolExecutor, TopologyMetrics, TopicSource, StreamsBuilder, base URLs.
- LLD method: clarify → nouns and states → pure rules → ports → patterns → one sequence with failures → tests.