On this page

LLD Practice: Easy

These problems build your LLD muscle memory. Each problem is self-contained — you should be able to design and implement any of them in 30-45 minutes. For each problem, read the requirements, study the class diagram hint, then try to implement it yourself before looking at the key interfaces.

The page started with 10 utility-style problems (Problems 1–10). Problems 11–14 add four classic domain case studies as warm-ups, because interviewers ask those as often as the utilities. The ladder below orders all 14 from easiest to hardest. When you finish it, move on to LLD Practice: Medium, then LLD Practice: Hard.

The ladder

#ProblemWhat it practisesTime boxFull case study
1Tic-Tac-Toe (P11)Entities vs value objects, O(1) win check, Strategy for players25 minTic-Tac-Toe
2Logger Framework (P1)Strategy (formatters), Chain of Responsibility (filters), a thread-safe handler30 minLogger
3Iterator Pattern (P3)Iterator, wrapping iterators Decorator-style, lazy evaluation30 min—
4Event Emitter (P4)Observer, listeners changing the list during emit, error isolation30 minPub-Sub
5Snake & Ladders (P12)Modelling, an injectable dice for tests, turn loop30 minSnake & Ladders
6Config Manager (P7)Precedence merge, Observer, the Singleton debate35 min—
7In-Memory Cache with TTL (P2)Map + doubly linked list, lazy expiry, Strategy for eviction, one lock40 minLRU Cache, KV Store
8Rate Limiter (P5)Strategy (algorithms), per-key state, injected clock, check-then-act races40 minRate Limiter
9Retry Mechanism (P6)Decorator, Strategy (backoff), injected sleep and randomness35 min—
10Vending Machine (P13)State pattern, money as integers, refunds40 minVending Machine
11In-Process Pub-Sub (P9)Observer, per-subscriber queues, retries and a dead letter queue45 minPub-Sub
12Connection Pool (P8)Object Pool, wait queue, timeouts, leaks45 min—
13Parking Lot (P14)Strategy (spot choice), Factory, atomic spot allocation45 minParking Lot
14Task Runner (P10)DAG, cycle detection, semaphore, cancellation45 minTask Scheduler

How to use this ladder

  1. Go in order. Each rung reuses something from the one before. The Logger's handler list comes back as the Event Emitter's listener list, and the Event Emitter grows into Pub-Sub.
  2. Set a timer for the time box. Follow the LLD Interview Framework: requirements, entities, class diagram, then the core code. Stop when the timer rings, even if you aren't finished. Running out of time is the skill being trained.
  3. Open "Hints" only when stuck for more than five minutes. Open "Solution outline" only after the timer, and compare it with what you built. Write down the one thing you missed.
  4. For rungs with a full case study, read the case study after your attempt, not before. It has complete Java, Python and TypeScript code to check yourself against.
  5. Move to Medium once you can do rungs 10–14 inside the time box without opening the hints.

Problem 1: Logger Framework

Build a configurable logging framework that supports multiple log levels, output destinations, and formatters.

Requirements

  • Support log levels: DEBUG, INFO, WARN, ERROR, FATAL
  • Multiple output destinations: Console, File, HTTP endpoint
  • Configurable log format (JSON, plain text)
  • Filter by minimum log level
  • Thread-safe logging
  • Support for structured metadata (key-value pairs)

Class Diagram Hint

classDiagram
    class Logger {
        -handlers: LogHandler[]
        -minLevel: LogLevel
        +debug(message, metadata)
        +info(message, metadata)
        +warn(message, metadata)
        +error(message, metadata)
        +addHandler(handler)
    }

    class LogHandler {
        <<interface>>
        +handle(entry: LogEntry)
    }

    class LogFormatter {
        <<interface>>
        +format(entry: LogEntry): string
    }

    class ConsoleHandler {
        -formatter: LogFormatter
        +handle(entry: LogEntry)
    }

    class FileHandler {
        -filePath: string
        -formatter: LogFormatter
        +handle(entry: LogEntry)
    }

    class JSONFormatter {
        +format(entry: LogEntry): string
    }

    class TextFormatter {
        +format(entry: LogEntry): string
    }

    Logger --> LogHandler
    ConsoleHandler ..|> LogHandler
    FileHandler ..|> LogHandler
    ConsoleHandler --> LogFormatter
    FileHandler --> LogFormatter
    JSONFormatter ..|> LogFormatter
    TextFormatter ..|> LogFormatter

Key Interfaces

enum LogLevel { DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3, FATAL = 4 }

interface LogEntry {
  level: LogLevel;
  message: string;
  timestamp: Date;
  metadata?: Record<string, unknown>;
}

interface LogHandler {
  handle(entry: LogEntry): void;
}

interface LogFormatter {
  format(entry: LogEntry): string;
}

Approach

  • Strategy Pattern for formatters — swap formatting logic without changing handlers
  • Observer Pattern for handlers — logger pushes entries to all registered handlers
  • Chain of Responsibility (optional) — handlers can filter which entries they process
  • Use a LogLevel enum with numeric values for easy comparison (if (entry.level >= this.minLevel))
Hints
  • Split the work into three questions: should this entry be logged? (level filter), what does it look like? (formatter), and where does it go? (handler). Each question gets its own interface.
  • Give every handler its own optional minimum level. The console might show DEBUG while the file only keeps WARN and above.
  • "Thread-safe" has two parts. The handler list must be safe to read while someone adds a handler, and two threads writing to one file must not interleave half-lines.
  • Don't build the formatted string before the level check. logger.debug(expensiveDump()) should cost nothing when DEBUG is off, so offer a lazy overload such as a supplier or lambda.
Solution outline
  • Entities: LogLevel (ordered enum), LogEntry (immutable value object: level, message, timestamp, metadata, logger name, thread), Logger, LogHandler, LogFormatter.
  • Key classes: Logger holds minLevel and a copy-on-write list of handlers. log(level, msg, meta) returns early if level < minLevel, builds one LogEntry and passes it to each handler. ConsoleHandler, FileHandler and HttpHandler each own a formatter and their own level.
  • Patterns: Strategy for formatters (JsonFormatter, TextFormatter). Observer-style fan-out from logger to handlers. Chain of Responsibility if the interviewer asks for filters that can stop an entry (a PII-scrubbing filter, then a sampling filter). See Chain of Responsibility and Strategy.
  • Concurrency: a copy-on-write handler list (CopyOnWriteArrayList in Java) makes addHandler safe during logging. Each FileHandler has its own lock around write-and-flush, so a slow file doesn't block the console. For throughput, add an AsyncHandler decorator that pushes entries onto a bounded queue drained by one worker thread. Decide what happens when the queue is full: block, or drop and count.
  • Singleton? Offer a LoggerFactory.getLogger(name) registry instead of one global logger. Tests can then inject a logger with an in-memory handler.
  • Edge cases: a handler that throws must not stop the other handlers or crash the caller. Metadata must be copied so later mutation by the caller doesn't change an entry already queued. Flush on shutdown.
  • Full version: Design a Logger.

Problem 2: In-Memory Cache with TTL

Build a cache that stores key-value pairs with time-to-live (TTL), eviction policies, and size limits.

Requirements

  • Get/Set/Delete operations with O(1) average time
  • Per-key TTL (time-to-live) — expired entries are not returned
  • Maximum capacity with LRU eviction when full
  • Cache statistics: hits, misses, evictions
  • Optional: support for cache-aside pattern (loader function on miss)

Class Diagram Hint

classDiagram
    class Cache~K, V~ {
        -store: Map~K, CacheEntry~
        -capacity: number
        -evictionPolicy: EvictionPolicy
        -stats: CacheStats
        +get(key: K): V | undefined
        +set(key: K, value: V, ttl?: number)
        +delete(key: K): boolean
        +clear()
        +size(): number
        +getStats(): CacheStats
    }

    class CacheEntry~V~ {
        -value: V
        -expiresAt: number
        -accessedAt: number
        -createdAt: number
        +isExpired(): boolean
    }

    class EvictionPolicy {
        <<interface>>
        +onAccess(key)
        +onInsert(key)
        +evict(): key
    }

    class LRUPolicy {
        -order: DoublyLinkedList
        +onAccess(key)
        +evict(): key
    }

    Cache --> CacheEntry
    Cache --> EvictionPolicy
    LRUPolicy ..|> EvictionPolicy

Key Interfaces

interface CacheOptions<K, V> {
  capacity: number;
  defaultTtl?: number;  // milliseconds
  evictionPolicy?: 'lru' | 'lfu' | 'fifo';
  onEvict?: (key: K, value: V) => void;
  loader?: (key: K) => Promise<V>;  // Cache-aside loader
}

interface CacheStats {
  hits: number;
  misses: number;
  evictions: number;
  size: number;
  hitRate: number;
}

Approach

  • Use a Map for O(1) lookups combined with a doubly linked list for LRU ordering
  • Lazy expiration: check TTL on get(), do not run a background cleanup timer
  • Optional: periodic cleanup via setInterval to prevent memory leaks from never-accessed expired entries
  • The LRU eviction uses the classic Map + DoublyLinkedList pattern (same as LeetCode #146)
Hints
  • Start without TTL. Get plain LRU working with a hash map from key to list node and a doubly linked list ordered by recency. Then add expiresAt to the node.
  • Expired entries still take space until something touches them. Decide what size() means: entries stored, or entries that are still live?
  • Inject a clock (() => number) so tests can jump forward in time instead of sleeping.
  • When the cache is full and you insert, evict an expired entry first if you can find one cheaply, and fall back to the least recently used one.
Solution outline
  • Entities: Cache<K, V>, Node<K, V> (key, value, expiresAt, prev, next), CacheStats, EvictionPolicy.
  • Core operations:
    • get(k): look up the node. If it's missing, count a miss. If it's expired, unlink it, remove it, and count a miss. Otherwise move it to the head and count a hit.
    • set(k, v, ttl): if the key exists, update it and move it to the head. Otherwise, if size == capacity, evict the tail. Then insert at the head.
    • All of these are O(1).
  • Patterns: Strategy for eviction (LruPolicy, LfuPolicy, FifoPolicy) behind onAccess, onInsert, onRemove and victim. Cache-aside loader as an optional function. Decorator if the interviewer wants stats or logging layered on without touching the core. See Strategy.
  • Concurrency: even get changes the list (move to head), so a read-write lock doesn't help. Use one mutex around map and list. For more throughput, split the cache into N independent shards by key hash, each with its own lock and capacity. The loader must not run under the lock. Use a per-key "in-flight" future so 100 concurrent misses for the same key trigger one load, not 100.
  • Edge cases: capacity 0, TTL 0 or negative, set on an existing key with a new TTL, a loader that throws (don't cache the failure, or cache it briefly on purpose), and the onEvict callback firing outside the lock.
  • Full versions: LRU Cache and the In-Memory KV Store with TTL and transactions.

Problem 3: Iterator Pattern

Design a generic iterator that supports iteration over different data structures (arrays, linked lists, trees) with a unified interface.

Requirements

  • Unified Iterator interface: hasNext(), next(), reset()
  • Support iterating arrays, linked lists, binary trees (in-order)
  • Composable: FilterIterator, MapIterator, TakeIterator
  • Lazy evaluation — don't traverse until next() is called
  • Support for for...of protocol

Key Interfaces

interface Iterator<T> {
  hasNext(): boolean;
  next(): T;
  reset(): void;
  [Symbol.iterator](): Iterator<T>;
}

// Composable iterators
class FilterIterator<T> implements Iterator<T> {
  constructor(private source: Iterator<T>, private predicate: (item: T) => boolean) {}

  hasNext(): boolean { /* find next matching element */ }
  next(): T { /* return next matching element */ }
}

class MapIterator<T, U> implements Iterator<U> {
  constructor(private source: Iterator<T>, private transform: (item: T) => U) {}
}

class TakeIterator<T> implements Iterator<T> {
  constructor(private source: Iterator<T>, private count: number) {}
}

Approach

  • Iterator Pattern — classic GoF pattern providing uniform traversal
  • Lazy evaluation means FilterIterator only advances the source iterator when next() is called
  • Composition: new TakeIterator(new FilterIterator(new ArrayIterator(data), fn), 10) takes 10 filtered items
  • Tree iterators use an explicit stack (not recursion) to maintain state between next() calls

Correction (2026-11-10): `for...of` needs the JavaScript iterator protocol

The interface above declares [Symbol.iterator](): Iterator<T>, returning the same object whose next() returns a bare T. for...of calls next() and expects { value, done }, so the loop would never see done: true. Also, in a script file without imports or exports, a top-level interface Iterator<T> merges with TypeScript's built-in global Iterator instead of replacing it. Keep the cursor-style API (hasNext, next, reset) under a different name, and adapt it to for...of with a generator:

// A cursor-style interface, named so it can't merge with TypeScript's global Iterator.
interface Cursor<T> extends Iterable<T> {
  hasNext(): boolean;
  next(): T;
  reset(): void;
}

class ArrayCursor<T> implements Cursor<T> {
  private i = 0;
  constructor(private readonly items: readonly T[]) {}
  hasNext(): boolean { return this.i < this.items.length; }
  next(): T {
    if (!this.hasNext()) throw new Error("no more elements");
    return this.items[this.i++];
  }
  reset(): void { this.i = 0; }
  // for...of needs the JS protocol ({ value, done }); a generator adapts hasNext/next to it.
  *[Symbol.iterator](): Generator<T> { while (this.hasNext()) yield this.next(); }
}

class FilterCursor<T> implements Cursor<T> {
  private lookahead: { value: T } | null = null; // a box, so T may itself be undefined
  constructor(private readonly source: Cursor<T>, private readonly keep: (item: T) => boolean) {}
  hasNext(): boolean {
    // Pull from the source only until one match is buffered: lazy, and hasNext() is idempotent.
    while (this.lookahead === null && this.source.hasNext()) {
      const item = this.source.next();
      if (this.keep(item)) this.lookahead = { value: item };
    }
    return this.lookahead !== null;
  }
  next(): T {
    if (!this.hasNext()) throw new Error("no more elements");
    const { value } = this.lookahead!;
    this.lookahead = null;
    return value;
  }
  reset(): void { this.lookahead = null; this.source.reset(); }
  *[Symbol.iterator](): Generator<T> { while (this.hasNext()) yield this.next(); }
}

const evens = new FilterCursor(new ArrayCursor([1, 2, 3, 4, 5, 6]), (n) => n % 2 === 0);
const out: number[] = [];
for (const n of evens) out.push(n);
console.log(out); // [ 2, 4, 6 ]
Hints
  • The hard part of FilterIterator is hasNext(). You can't answer it without pulling items from the source until one matches, so you need a one-item lookahead buffer.
  • Calling hasNext() twice in a row must not skip an element. Write that as your first test.
  • For the in-order tree iterator, push the left spine of the root onto a stack. next() pops a node, then pushes the left spine of its right child.
  • Decide what reset() means for a wrapper: it has to reset its source and clear its own buffer.
Solution outline
  • Entities: Cursor<T> (the interface), the sources ArrayCursor, LinkedListCursor and InOrderTreeCursor, and the wrappers FilterCursor, MapCursor and TakeCursor.
  • Key idea: every wrapper holds a source cursor and does the minimum work per next(). MapCursor.next() is transform(source.next()). TakeCursor counts down and reports hasNext() === false at zero without touching the source. FilterCursor keeps the boxed lookahead shown above.
  • Patterns: Iterator for uniform traversal. The wrappers are Decorators: same interface, extra behaviour (Decorator). A fluent from(data).filter(f).map(g).take(10) builder on top is a nice touch, if there's time.
  • Concurrency: iterators are single-threaded by design. Say what happens if the underlying collection changes during iteration: fail fast with a modification counter (as Java's ConcurrentModificationException does), or iterate a snapshot.
  • Edge cases: next() after exhaustion throws, empty sources, take(0), a filter that matches nothing on an infinite source (it never returns, so document it), and undefined as a legitimate element (hence the box).

Problem 4: Event Emitter

Build an event emitter (pub-sub within a single process) that supports typed events, once listeners, and error handling.

Requirements

  • on(event, listener) — register a listener
  • off(event, listener) — remove a listener
  • emit(event, ...args) — trigger all listeners for an event
  • once(event, listener) — listener fires once then auto-removes
  • Support wildcard listeners (* matches all events)
  • Error handling: if a listener throws, other listeners still execute

Class Diagram Hint

classDiagram
    class EventEmitter {
        -listeners: Map~string, Listener[]~
        +on(event, listener): Unsubscribe
        +off(event, listener)
        +once(event, listener): Unsubscribe
        +emit(event, ...args): boolean
        +listenerCount(event): number
        +removeAllListeners(event?)
    }

    class Listener {
        -callback: Function
        -once: boolean
        +invoke(...args)
    }

    EventEmitter --> Listener

Key Interfaces

type EventListener<T = any> = (...args: T[]) => void;
type Unsubscribe = () => void;

interface IEventEmitter {
  on(event: string, listener: EventListener): Unsubscribe;
  off(event: string, listener: EventListener): void;
  once(event: string, listener: EventListener): Unsubscribe;
  emit(event: string, ...args: any[]): boolean;
  listenerCount(event: string): number;
  removeAllListeners(event?: string): void;
}

Approach

  • Store listeners in a Map<string, Array<{ callback, once }>> for O(1) event lookup
  • once() wraps the callback: on first invocation, it calls the real callback then removes itself
  • on() returns an unsubscribe function (closure that calls off())
  • Error isolation: wrap each listener invocation in try/catch so one failing listener does not prevent others from executing
  • Wildcard: maintain a separate * listener array; emit() always invokes these
Hints
  • What happens if a listener calls off() on itself, or on() for the same event, while emit() is looping over the list? Decide before you code.
  • once() wraps the callback. So off(event, originalCallback) won't find the wrapper unless you remember which original each wrapper belongs to.
  • Should emit return whether anyone listened? Node's EventEmitter returns a boolean, which is handy for "no handler for this event" warnings.
  • Listener errors: swallow and log, rethrow after all listeners ran (an aggregate error), or send them to a special error event?
Solution outline
  • Entities: EventEmitter, ListenerRecord (callback, once flag, original callback for once wrappers).
  • emit(event, ...args): take a snapshot of listeners.get(event) plus the wildcard list, then iterate the snapshot. Listeners added during an emit run from the next emit on, and listeners removed during an emit may still run this once. Both choices are fine if you state them. Remove once records before calling them, so a listener that re-emits the same event doesn't fire twice.
  • off: match by record.callback === cb || record.original === cb. Delete the map entry when its list becomes empty, so the map doesn't grow forever.
  • Pattern: Observer. Typed events in TypeScript: class Emitter<E extends Record<string, unknown[]>> with on<K extends keyof E>(event: K, fn: (...args: E[K]) => void).
  • Concurrency: in Node, everything happens on one thread, so the snapshot is all you need. In Java, store each list as a CopyOnWriteArrayList inside a ConcurrentHashMap. Reads (emits) are lock-free and writes copy, which is right for an emitter where emits far outnumber subscriptions.
  • Edge cases: the same callback registered twice (fires twice, or deduplicate?), the unsubscribe function called twice (must be harmless), a listener that throws, and memory leaks from forgotten listeners (warn above a maximum listener count, as Node does).
  • Next step up: Pub-Sub adds topics, asynchronous delivery and retries.

Problem 5: Rate Limiter

Design a rate limiter that supports fixed window, sliding window, and token bucket algorithms.

Requirements

  • Multiple algorithms: Fixed Window, Sliding Window Log, Token Bucket
  • Configurable: requests per window, window size, burst capacity
  • Thread-safe (or concurrent-safe in single-threaded async)
  • Return remaining quota and reset time in responses
  • Support per-key rate limiting (by user, IP, API key)

Class Diagram Hint

classDiagram
    class RateLimiter {
        <<interface>>
        +tryAcquire(key: string): RateLimitResult
        +getRemainingQuota(key: string): number
    }

    class FixedWindowLimiter {
        -windows: Map~string, WindowState~
        -limit: number
        -windowMs: number
        +tryAcquire(key): RateLimitResult
    }

    class SlidingWindowLimiter {
        -logs: Map~string, number[]~
        -limit: number
        -windowMs: number
        +tryAcquire(key): RateLimitResult
    }

    class TokenBucketLimiter {
        -buckets: Map~string, Bucket~
        -maxTokens: number
        -refillRate: number
        +tryAcquire(key): RateLimitResult
    }

    FixedWindowLimiter ..|> RateLimiter
    SlidingWindowLimiter ..|> RateLimiter
    TokenBucketLimiter ..|> RateLimiter

Key Interfaces

interface RateLimitResult {
  allowed: boolean;
  remaining: number;
  retryAfterMs?: number;
  limit: number;
  resetAt: Date;
}

interface RateLimiterConfig {
  algorithm: 'fixed-window' | 'sliding-window' | 'token-bucket';
  limit: number;
  windowMs?: number;         // For window-based
  refillRate?: number;       // For token bucket: tokens per second
  burstCapacity?: number;    // For token bucket: max tokens
}

Approach

  • Fixed Window: divide time into fixed intervals, count requests per interval, reset at window boundary
  • Sliding Window Log: store timestamp of each request, count requests in the trailing window
  • Token Bucket: bucket refills at fixed rate, each request consumes a token, burst up to max capacity
  • Use Map<string, State> for per-key tracking. Clean up stale entries periodically.
Hints
  • Inject a clock. Every rate limiter test is about time, and you can't test token refill if you call Date.now() directly.
  • Token bucket doesn't need a timer. Refill lazily when a request arrives: tokens = min(capacity, tokens + elapsed * rate).
  • "Read count, compare, increment" is a check-then-act race. Two threads can both see 9 of 10 and both get in.
  • Fixed window lets through up to 2× the limit around a boundary (10 requests at 0:59, 10 more at 1:00). Be ready to explain this and how the sliding window fixes it.
Solution outline
  • Entities: RateLimiter (interface), FixedWindowLimiter, SlidingWindowLogLimiter, TokenBucketLimiter, RateLimitResult, and a factory that builds one from RateLimiterConfig.
  • Per-key state: Map<key, WindowState | Deque<timestamp> | Bucket>. A sliding log stores up to limit timestamps per key, so trim old ones from the front on every call. A sliding window counter (weighted previous window plus current window) gets close to the same accuracy with O(1) memory. Mention it as the trade-off.
  • Pattern: Strategy for the algorithm. A Decorator or middleware applies it to a handler. Add a composite limiter if the interviewer wants "10 per second AND 1,000 per day".
  • Concurrency: the whole read-modify-write for one key must be atomic. Options: ConcurrentHashMap.compute(key, ...) in Java, a lock per key (striped locks, so the number of locks stays bounded), or synchronized on the bucket object. A single global lock is correct but serialises unrelated users. Say that, then shard. In a distributed setting the state moves to Redis, and a Lua script makes the update atomic.
  • Edge cases: retryAfterMs for each algorithm, clock going backwards (clamp elapsed to ≥ 0), idle keys piling up (evict buckets that are full and untouched), and a cost per request (a bulk call uses 5 tokens).
  • Full version: Rate Limiter.

Problem 6: Retry Mechanism

Design a retry framework with exponential backoff, jitter, circuit breaker integration, and configurable retry conditions.

Requirements

  • Configurable max retries, base delay, max delay
  • Exponential backoff with jitter (full, equal, decorrelated)
  • Retry only on specific errors (configurable predicate)
  • Abort retry on specific errors (non-retryable errors)
  • Optional circuit breaker integration
  • Callbacks: onRetry, onSuccess, onFailure

Key Interfaces

interface RetryConfig {
  maxRetries: number;
  baseDelay: number;         // ms
  maxDelay: number;          // ms
  backoffMultiplier: number; // typically 2
  jitter: 'none' | 'full' | 'equal' | 'decorrelated';
  retryOn?: (error: Error) => boolean;
  abortOn?: (error: Error) => boolean;
  onRetry?: (error: Error, attempt: number, delay: number) => void;
}

class RetryExecutor {
  constructor(private config: RetryConfig) {}

  async execute<T>(fn: () => Promise<T>): Promise<T> {
    // Implement retry loop with backoff
  }

  private calculateDelay(attempt: number): number {
    const exponentialDelay = this.config.baseDelay * Math.pow(this.config.backoffMultiplier, attempt);
    const clampedDelay = Math.min(exponentialDelay, this.config.maxDelay);

    switch (this.config.jitter) {
      case 'none': return clampedDelay;
      case 'full': return Math.random() * clampedDelay;
      case 'equal': return clampedDelay / 2 + Math.random() * (clampedDelay / 2);
      case 'decorrelated': return Math.min(this.config.maxDelay,
        this.config.baseDelay + Math.random() * (clampedDelay * 3 - this.config.baseDelay));
    }
  }
}

Approach

  • Jitter prevents the thundering herd — without it, all retries happen at the same time
  • Decorrelated jitter (AWS recommendation) gives the best distribution
  • retryOn predicate lets you skip retries on non-transient errors (e.g., 400 Bad Request)
  • The retry executor is a decorator — it wraps any async function transparently

Correction (2026-11-10): decorrelated jitter needs the previous delay

The 'decorrelated' branch above computes from clampedDelay, which depends only on the attempt number. That makes it exponential backoff times a random factor between roughly 1/3 and 3. Decorrelated jitter, as described in Marc Brooker's AWS Architecture Blog post "Exponential Backoff And Jitter" (2015), is sleep = min(cap, random_between(base, previousSleep * 3)). Each delay grows from the previous random delay, so it needs state. That post also found Full Jitter and Decorrelated Jitter roughly tied, with Equal Jitter behind them. So "best distribution" above overstates it: either of the two is a good default.

// Decorrelated jitter keeps the previous delay as state:
//   sleep = min(cap, random_between(base, previousSleep * 3))
class DecorrelatedJitter {
  private prev: number;
  constructor(
    private readonly base: number,
    private readonly cap: number,
    private readonly random: () => number = Math.random, // inject for tests
  ) {
    this.prev = base;
  }
  nextDelay(): number {
    this.prev = Math.min(this.cap, this.base + this.random() * (this.prev * 3 - this.base));
    return this.prev;
  }
  reset(): void { this.prev = this.base; }
}

const worstCase = new DecorrelatedJitter(100, 10_000, () => 1);
console.log([1, 2, 3, 4, 5].map(() => worstCase.nextDelay())); // [ 300, 900, 2700, 8100, 10000 ]

Create one DecorrelatedJitter per call to execute(), not one per executor. Otherwise concurrent calls share and corrupt each other's prev.

Hints
  • Separate when to retry (a predicate on the error), how long to wait (a backoff strategy) and how to wait (an injectable sleep). Then tests can run in milliseconds.
  • Count carefully: maxRetries = 3 means up to 4 attempts. Write it as a test.
  • What does the caller get when every attempt fails: the last error, or an aggregate of all of them?
  • Retrying a non-idempotent call (charge a card) can duplicate the side effect. Who is responsible for idempotency, the executor or the caller?
Solution outline
  • Entities: RetryExecutor, RetryPolicy (max attempts, retryOn, abortOn), BackoffStrategy (Fixed, Exponential, FullJitter, DecorrelatedJitter), Sleeper (real or fake), and an optional CircuitBreaker.
  • Loop: for attempt 0..maxRetries, call fn() and return on success. On error: if abortOn(err) or !retryOn(err) or this was the last attempt, rethrow. Otherwise compute the delay, call onRetry(err, attempt, delay), then await sleep(delay). Respect an AbortSignal so a cancelled request stops retrying.
  • Patterns: Decorator, because withRetry(fn) has the same signature as fn. Strategy for backoff. The circuit breaker is a State machine (CLOSED, OPEN, HALF_OPEN) consulted before each attempt. When it's OPEN, fail fast without calling fn.
  • Concurrency: the executor itself should be stateless and shareable. Per-call state (attempt number, previous delay) lives in local variables. A shared circuit breaker is shared state: guard its counters with atomics, and let only one probe request through in HALF_OPEN.
  • Edge cases: honour a server's Retry-After header over your own backoff, an overall deadline (stop retrying when the remaining time is shorter than the next delay), errors thrown synchronously by fn, and maxRetries = 0.

Problem 7: Config Manager

Design a configuration manager that supports multiple sources, environment overrides, type validation, and hot reloading.

Requirements

  • Load config from: JSON file, environment variables, command-line args
  • Priority order: CLI args > env vars > config file > defaults
  • Type-safe access with validation
  • Hot reload: detect config file changes and update without restart
  • Support nested config keys (e.g., database.host)
  • Singleton access pattern

Key Interfaces

interface ConfigSource {
  name: string;
  priority: number;  // Higher overrides lower
  load(): Promise<Record<string, unknown>>;
  watch?(onChange: () => void): void;
}

interface ConfigSchema {
  [key: string]: {
    type: 'string' | 'number' | 'boolean' | 'object';
    required?: boolean;
    default?: unknown;
    validate?: (value: unknown) => boolean;
    env?: string;  // MAP to environment variable
  };
}

class ConfigManager {
  private static instance: ConfigManager;
  private sources: ConfigSource[] = [];
  private resolved: Map<string, unknown> = new Map();

  static getInstance(): ConfigManager { /* Singleton */ }

  addSource(source: ConfigSource): void;
  get<T>(key: string): T;
  getOrDefault<T>(key: string, defaultValue: T): T;
  reload(): Promise<void>;
  onChange(key: string, callback: (oldValue, newValue) => void): void;
}

Approach

  • Template Method Pattern for config sources — each source implements load() differently
  • Observer Pattern for change notifications — services subscribe to config key changes
  • Merge configs by priority: iterate sources from lowest to highest, deep-merge objects
  • Validate against schema on load — fail fast with clear error messages for missing/invalid config

Correction (2026-11-10): that's polymorphism behind an interface, not Template Method

ConfigSource above is an interface, and each source implements load() its own way. That's plain polymorphism, closest to Strategy. Template Method would mean an abstract base class with a fixed algorithm, such as loadAndValidate() calling read() then parse() then normalize(), where subclasses override only some of the steps. That's a reasonable design too, for example a FileSource base with JsonFileSource and YamlFileSource overriding parse(). But it's a different pattern from the one shown in the code.

Hints
  • Flatten nested config to dotted keys (database.host) once, at merge time. Then get is a single map lookup.
  • Environment variables are always strings. Where does "5432" become the number 5432: in the source or in the schema?
  • Hot reload must swap the whole resolved map atomically. A reader must never see the new host with the old port.
  • Ask yourself whether getInstance() will make your tests painful. (It will. Plan for it.)
Solution outline
  • Entities: ConfigSource (DefaultsSource, FileSource, EnvSource, CliSource), ConfigSchema, ConfigManager, ChangeListener.
  • Load: sort sources by priority, load each, flatten, and merge low to high so later ones win. Then coerce types and validate against the schema, collecting all errors before failing, so one run tells the operator everything that's wrong. Store the result as an immutable map.
  • Reload: build a new map off to the side, validate it, and if it's valid, swap one reference (an AtomicReference in Java). Then diff the old and new maps and notify listeners per changed key. If validation fails, keep the old config and log. Never apply half a reload.
  • Patterns: Observer for onChange. Singleton is what the problem asks for, but argue for creating one instance at startup and passing it in (dependency injection). A static getInstance() hides a dependency and leaks state between tests. If you must keep it, add a resetForTests() hook.
  • Concurrency: readers are lock-free through the atomic reference. Reloads (file watcher plus manual reload()) are serialised by a single lock or a single-threaded executor, so two reloads can't race. Listeners run after the swap and outside any lock.
  • Edge cases: a required key missing in every source, a key that's an object in one source and a scalar in another, secrets that must not be logged in validation errors, and a file watcher firing twice for one save (debounce it).

Problem 8: Connection Pool

Design a database connection pool with configurable min/max connections, health checking, and connection recycling.

Requirements

  • Configurable min/max pool size
  • Acquire/release connection with timeout
  • Health checking: periodic ping to detect stale connections
  • Connection recycling: close connections older than max lifetime
  • Wait queue: if pool is exhausted, requests wait (with timeout)
  • Pool statistics: active, idle, waiting, total

Class Diagram Hint

classDiagram
    class ConnectionPool {
        -idle: Deque~PooledConnection~
        -active: Set~PooledConnection~
        -waiting: Queue~Resolver~
        -config: PoolConfig
        +acquire(timeout?): Promise~Connection~
        +release(connection)
        +destroy()
        +getStats(): PoolStats
    }

    class PooledConnection {
        -connection: Connection
        -createdAt: number
        -lastUsedAt: number
        -lastHealthCheck: number
        +isExpired(): boolean
        +isHealthy(): Promise~boolean~
    }

    ConnectionPool --> PooledConnection

Key Interfaces

interface PoolConfig {
  min: number;           // Minimum idle connections
  max: number;           // Maximum total connections
  acquireTimeout: number; // ms to wait for a connection
  idleTimeout: number;    // ms before idle connection is closed
  maxLifetime: number;    // ms before connection is recycled
  healthCheckInterval: number; // ms between health checks
  createConnection: () => Promise<Connection>;
  destroyConnection: (conn: Connection) => Promise<void>;
  validateConnection: (conn: Connection) => Promise<boolean>;
}

interface PoolStats {
  total: number;
  active: number;
  idle: number;
  waiting: number;
  created: number;   // lifetime total
  destroyed: number; // lifetime total
}

Approach

  • Object Pool Pattern — reuse expensive-to-create connections
  • Idle connections stored in a deque: LIFO for better cache locality (most recently used connection likely has warm TCP state)
  • Background task: health check idle connections, close expired ones, maintain minimum pool size
  • Wait queue: when pool is full, acquire() returns a Promise that resolves when a connection is released
Hints
  • Count total = idle + active + creating. If you forget connections that are still being created, a burst of acquire calls will overshoot max.
  • When a connection is released and someone is waiting, hand it straight to the first waiter. Don't put it in the idle deque for someone else to steal.
  • A waiter that times out must be removed from the queue. Otherwise a later release resolves a promise nobody is listening to, and that connection leaks.
  • Validate on borrow, on return, or in the background? Each has a cost. Pick one and say why.
Solution outline
  • Entities: ConnectionPool, PooledConnection (wraps the real connection: createdAt, lastUsedAt, a borrowed flag), PoolConfig, PoolStats, Waiter (resolve, reject, timer).
  • acquire(timeout): (1) pop idle connections until you find one that isn't expired, destroying expired ones as you go. (2) If total < max, reserve a slot (creating++) and create a new one. (3) Otherwise enqueue a Waiter with a timeout that removes it and rejects.
  • release(conn): if it's broken or expired, destroy it and, if there's a waiter, create a fresh connection for them. Else, if there's a waiter, hand the connection over directly. Else push it onto the idle deque (LIFO). Releasing a connection twice is a bug: detect it with the borrowed flag.
  • Pattern: Object Pool. A Proxy around the connection makes close() return it to the pool instead of closing the socket. That's how HikariCP and most JDBC pools behave.
  • Concurrency: in Java, a Semaphore(max) bounds total connections, and a lock (or ConcurrentLinkedDeque plus careful counters) protects the idle deque. In Node there's one thread, but createConnection is async: increment creating before the await, or two callers both think there's room.
  • Maintenance task: every healthCheckInterval, ping idle connections, close ones past idleTimeout while staying at or above min, and recycle ones past maxLifetime. Never touch connections that are borrowed.
  • Edge cases: destroy() while connections are borrowed (reject all waiters, close idle connections now and borrowed ones on return), createConnection failing (release the reserved slot, then reject or retry), and min > max in config (reject at construction).

Problem 9: In-Process Pub-Sub

Design an in-process publish-subscribe system with topics, subscriptions, and message ordering.

Requirements

  • Create/delete topics
  • Subscribe/unsubscribe to topics
  • Publish messages to a topic — delivered to all subscribers
  • Message ordering guaranteed within a topic
  • Support for message filtering (subscribers specify filter criteria)
  • Dead letter handling for failed message processing
  • At-least-once delivery semantics

Key Interfaces

interface Message<T = unknown> {
  id: string;
  topic: string;
  payload: T;
  timestamp: Date;
  headers: Record<string, string>;
}

interface Subscription {
  id: string;
  topic: string;
  handler: (message: Message) => Promise<void>;
  filter?: (message: Message) => boolean;
  maxRetries?: number;
}

interface PubSub {
  createTopic(name: string): void;
  deleteTopic(name: string): void;
  publish<T>(topic: string, payload: T, headers?: Record<string, string>): string;
  subscribe(topic: string, handler: MessageHandler, options?: SubscriptionOptions): string;
  unsubscribe(subscriptionId: string): void;
}

Approach

  • Topics stored in a Map<string, Topic> where each Topic has a list of subscriptions
  • Message ordering: process subscribers sequentially for each message (or use per-subscriber queue)
  • Dead letter: after maxRetries failures, move message to a DLQ topic
  • Message IDs enable idempotent processing (subscribers can track processed IDs)
Hints
  • If publish calls every handler inline, one slow subscriber slows the publisher and every other subscriber. Give each subscription its own queue.
  • "Ordering within a topic" plus "retry on failure" pull against each other. While message 5 is being retried, may message 6 be delivered to that subscriber?
  • At-least-once means a handler can see the same message twice. Whose job is deduplication?
  • What happens to messages published to a topic with no subscribers: dropped, or kept for subscribers who join later?
Solution outline
  • Entities: Broker, Topic (name, subscriptions), Subscription (handler, filter, maxRetries, its own FIFO queue and worker), Message (immutable: id, topic, payload, headers, timestamp, attempt count), and a dead letter topic.
  • Publish: look up the topic, stamp an id, and for each subscription whose filter matches, enqueue the message. Return the id at once.
  • Delivery: each subscription has one worker that takes messages from its queue in order. It calls the handler and, on failure, retries with backoff up to maxRetries, blocking the messages behind it. That is how ordering survives retries. After the last failure, it publishes to <topic>.dlq with the error in the headers and moves on.
  • Patterns: Observer at heart. Mediator if you frame the broker as decoupling publishers from subscribers. A filter is a predicate object (Specification-style).
  • Concurrency: the topic map is read-mostly, so use ConcurrentHashMap and copy-on-write subscription lists. Per-subscription queues are bounded blocking queues. Decide the policy when one is full: block the publisher (backpressure), drop the oldest, or reject. Unsubscribe must stop the worker and either drain or discard its queue.
  • Edge cases: deleting a topic with messages in flight, a handler that never returns (wrap it with a timeout), a filter that throws (treat as no match and log), and the DLQ itself failing (never retry DLQ delivery into the DLQ).
  • Full version: Pub-Sub / Message Broker.

Problem 10: Task Runner

Design a task runner that executes tasks with dependencies, parallelism, timeouts, and retry logic.

Requirements

  • Define tasks with dependencies (DAG)
  • Detect circular dependencies before execution
  • Execute independent tasks in parallel
  • Configurable concurrency limit
  • Per-task timeout and retry configuration
  • Task status tracking: pending, running, completed, failed, skipped
  • Cancel running execution

Class Diagram Hint

classDiagram
    class TaskRunner {
        -tasks: Map~string, TaskNode~
        -concurrency: number
        +addTask(task: TaskDefinition)
        +run(): Promise~ExecutionResult~
        +cancel()
    }

    class TaskNode {
        -id: string
        -execute: Function
        -dependencies: string[]
        -timeout: number
        -retries: number
        -status: TaskStatus
    }

    class ExecutionResult {
        -results: Map~string, TaskResult~
        -duration: number
        +succeeded(): boolean
        +getFailures(): TaskResult[]
    }

    TaskRunner --> TaskNode
    TaskRunner --> ExecutionResult

Key Interfaces

interface TaskDefinition {
  id: string;
  execute: (context: TaskContext) => Promise<unknown>;
  dependencies?: string[];
  timeout?: number;
  retries?: number;
  retryDelay?: number;
}

type TaskStatus = 'pending' | 'running' | 'completed' | 'failed' | 'skipped' | 'cancelled';

interface TaskContext {
  taskId: string;
  attempt: number;
  results: Map<string, unknown>;  // Results from dependency tasks
  signal: AbortSignal;            // For cancellation
}

Approach

  • Build a DAG from task definitions. Detect cycles using DFS with visited + inStack sets.
  • Use topological sort to determine execution order. Tasks with no unfinished dependencies can run in parallel.
  • Concurrency limiter: use a semaphore (counter + queue) to limit parallel tasks.
  • When a task fails after all retries, mark all dependent tasks as skipped.
  • Cancellation: set an AbortController, check signal.aborted in task execution.
Hints
  • Validate everything before running anything: unknown dependency ids, duplicate task ids, cycles. A cycle found halfway through execution is a much worse error.
  • You don't need a precomputed topological order. Keep an in-degree count per task. Whenever a task finishes, decrement its dependents' counts and start any that hit zero (Kahn's algorithm, run live).
  • The concurrency limit is a semaphore. In JavaScript that's a counter plus a queue of waiting starts.
  • A timeout doesn't stop a promise. It only stops you waiting for it. Pass the AbortSignal so the task can stop itself.
Solution outline
  • Entities: TaskRunner, TaskNode (definition, status, remaining dependency count, dependents list, attempts, result or error), ExecutionResult, TaskContext.
  • Validation: build adjacency from dependencies, then detect cycles with a three-colour DFS (white, grey, black), reporting the cycle path. Kahn's algorithm also works: if it can't consume every node, there's a cycle.
  • Run: push every task with in-degree 0 into a ready queue. A scheduler loop starts tasks while running < concurrency. Each task runs with retries and a timeout (Promise.race with a timer, plus abort). On success, store the result and release dependents whose count reaches 0. On final failure, mark the task failed and mark all its transitive dependents skipped. The run ends when nothing is running and nothing is ready.
  • Patterns: Command (each task is an executable object with retry metadata). State for the task status transitions (PENDING, RUNNING, then COMPLETED, FAILED, SKIPPED or CANCELLED). An Observer hook for progress events.
  • Concurrency: in Node, the counters are safe because there's one thread, but the order of awaits matters. In Java, use a fixed thread pool sized to the limit, with completion callbacks updating counts under one lock (or AtomicInteger per node). cancel() aborts the shared signal, stops scheduling new tasks and marks pending ones cancelled.
  • Edge cases: an empty task list, a task depending on itself, "fail fast" (cancel everything on the first failure) vs "continue" (run independent branches), and results from dependencies passed in through the context.
  • Full version: Task Scheduler adds delayed and recurring jobs.

Problem 11: Tic-Tac-Toe

Design an N×N tic-tac-toe game for two players, where either player can be a human or a computer.

Requirements

  • Board of size N (default 3), players take turns placing their mark
  • Detect a win (full row, column or either diagonal) or a draw after every move
  • Reject invalid moves: out of bounds, occupied cell, wrong player's turn, game already over
  • Players can be human (moves from input) or computer (moves from a strategy)
  • Optional: undo the last move
Hints
  • You don't need to scan the board after each move. Keep a counter per row, per column and per diagonal: add +1 for X and −1 for O. A counter reaching ±N is a win, in O(1).
  • Who owns the turn order: the Game or the Board? The board shouldn't know about players.
  • Make the computer player a strategy, so "random", "blocks your win" and "minimax" are swappable.
Solution outline
  • Entities: Game (board, players, current turn, status), Board (N×N cells, the counters), Player (name, mark, MoveStrategy), Move (row, col, mark: a value object), and GameStatus (IN_PROGRESS, X_WON, O_WON, DRAW).
  • Game.play(row, col): check the game is in progress and the cell is valid and empty, then place the mark, update four counters, and set the status (win if any counter's absolute value is N, draw if the move count is N²). Then switch turns.
  • Patterns: Strategy for computer players. Command with an undo stack if undo is asked for: undoing reverses the counters too.
  • Concurrency: usually none. If two clients play over a network, serialise moves through the Game (one lock or one actor) and check the turn inside the lock.
  • Edge cases: N = 1, a move after the game ended, and a draw detected on the very move that also wins (the win takes priority).
  • Full version: Tic-Tac-Toe.

Problem 12: Snake and Ladders

Design a snake and ladders game for 2–6 players on a 100-square board.

Requirements

  • Board with configurable snakes (head → tail) and ladders (bottom → top)
  • Players roll one die (configurable: more dice, different faces) and move in turn order
  • Landing on a snake head or ladder bottom moves the player to the other end
  • A player needs an exact roll to land on 100 (overshooting means no move)
  • First player to reach 100 wins; optionally keep playing for second and third place
Hints
  • Snakes and ladders are the same thing: a jump from one square to another. One Map<Integer, Integer> covers both.
  • Inject the dice. A test needs to say "roll 6, then 4" and check exactly where the player ends up.
  • Validate the board at construction: no jump starts on square 1 or 100, no two jumps start on the same square, and no chain that loops forever.
Solution outline
  • Entities: Game (board, a queue of players, a dice, winners), Board (size, a map of jumps), Player (name, position), Dice (an interface: roll()), and Jump (from, to).
  • Turn loop: take the next player from the queue, roll, and compute next = pos + roll. If next > size, stay. Otherwise follow jumps from next, apply the move, and record a win at size. Put the player back at the end of the queue unless they've finished.
  • Patterns: Strategy for dice (RandomDice, FixedSequenceDice for tests, CrookedDice that only rolls evens). An Observer for move events if there's a UI or a log.
  • Concurrency: none in the basic game. It's a turn-based loop on one thread.
  • Edge cases: a ladder that ends on a snake head (follow jumps until you stop), rolling three sixes in a row (a common house rule extension), and one player left (the game ends).
  • Full version: Snake & Ladders.

Problem 13: Vending Machine

Design a vending machine that sells products from slots, accepts coins and notes, and returns change.

Requirements

  • Slots hold products with a price and a quantity
  • User inserts money, selects a product, gets the product and change
  • Cancel at any time returns all inserted money
  • Reject selection when the product is sold out or the money isn't enough
  • Machine can't dispense if it can't make exact change
  • Admin can restock products and collect cash
Hints
  • The machine behaves differently depending on where it is in the flow (idle, has money, dispensing). That's the classic sign of the State pattern.
  • Store money as integer cents, never as floating point.
  • Making change: greedy works for standard coin sets like 1/5/10/25, but not for every set. With a limited coin inventory you may need to search. Check you can make change before taking the money.
Solution outline
  • Entities: VendingMachine (context: current state, inventory, coin box, balance), State (an interface: insert, select, cancel, dispense), IdleState, HasMoneyState, DispensingState, OutOfServiceState, Slot (product, price, quantity), Coin and Note (enum denominations), and ChangeMaker.
  • Flow: insert adds to the balance and moves to HasMoney. select checks stock, price and whether change can be made, then moves to Dispensing, decrements stock, pays out change and returns to Idle. cancel refunds the balance from any state that holds money.
  • Pattern: State. Each state class only implements the actions that make sense in it and rejects the rest with a clear error. Compare it with a big switch on an enum and say why State scales better as states are added.
  • Concurrency: a physical machine has one user, so put a single lock around every public method, or run commands one at a time on one thread. Admin restock while a sale is in progress waits for the sale to finish.
  • Edge cases: exact payment (no change), a sold-out product selected, coins of an unknown denomination, and running out of small coins for change.
  • Full version: Vending Machine.

Problem 14: Parking Lot

Design a parking lot with several floors, different spot sizes and different vehicle types, with tickets and fees.

Requirements

  • Floors contain spots of type SMALL, MEDIUM, LARGE (and optionally EV charging)
  • Vehicles: motorcycle, car, truck; a vehicle fits a spot of its size or larger
  • Entry issues a ticket with the assigned spot and entry time; exit computes a fee and frees the spot
  • Show free spots per floor and type
  • Several entry and exit gates operate at the same time
Hints
  • The interesting bug is two gates assigning the same spot at the same moment. Where does "find a free spot and mark it taken" become one atomic step?
  • Keep a set of free spots per type (or per floor and type), so finding a spot doesn't scan the whole lot.
  • Fees change more often than anything else. Put them behind an interface.
Solution outline
  • Entities: ParkingLot, Floor, ParkingSpot (id, type, an occupied flag), Vehicle (type, plate), Ticket (id, vehicle, spot, entry time), Gate, SpotAllocationStrategy, FeeStrategy.
  • Park: the strategy picks a spot from the free sets (nearest the gate, lowest floor, or smallest fitting size first). Remove it from the free set atomically, mark it occupied and issue a ticket. Unpark: compute the fee from the ticket and the injected clock, mark the spot free and add it back to the free set.
  • Patterns: Strategy for allocation and pricing. Factory Method for vehicles or spots if the interviewer adds types. Observer for a display board that shows free counts.
  • Concurrency: use one concurrent queue of free spots per spot type, and claim a spot with poll(). That's atomic, so two gates can never get the same spot. Or claim with a compare-and-set on the spot's occupied flag and retry on failure. A global lock is correct and simple, and fine for one lot. Say so before optimising.
  • Edge cases: a lot that's full for this vehicle type, a lost ticket (charge the daily maximum), a vehicle that's already inside trying to enter again, and a clock passing midnight in the fee rules.
  • Full version: Parking Lot, and the live walkthrough in Mock Interview: Parking Lot.

Practice Strategy

PhaseTimeFocus
Read5 minUnderstand requirements, identify patterns
Design10 minDraw class diagram, define interfaces
Implement20 minCore logic, happy path
Edge cases10 minError handling, concurrency, cleanup

Start with problems 1, 4, and 5 (Logger, Event Emitter, Rate Limiter) — they appear most frequently in interviews and teach patterns used in every other problem.

If you're working through the ladder instead, its order already puts those three early, with the warm-ups between them. Either route works. The ladder spreads the difficulty more evenly.