Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 57 ยท Practice and Interview Prep

Low-Level Design Exercises with Solutions

Six classic low-level design exercises with runnable Node.js solutions: ATM, notification service, rate limiter, logger framework, LRU cache and tic-tac-toe.

The projects in this chapter walked through full designs. This lesson is for practice. It gives you six well-known low-level design problems, each small enough to design in 30 to 45 minutes: an ATM, a notification service, a rate limiter, a logger framework, an LRU cache and tic-tac-toe. They show up in interviews again and again because each one has a clean core, a few places where patterns genuinely help, and a trap or two.

For every exercise you get the requirements, the questions a design should answer, and a short Node.js solution. The advice is the same as in How to Approach a Low-Level Design Problem: do the exercise yourself first, using the seven steps, and only then open the solution. These are in-memory sketches. A production ATM, notifier or logger needs hardware, queues, files and databases that cannot run on this site; the sketches isolate the design.

Six exercises

ATM State, cash dispensing, PIN limits.
Notifications Channels, templates, retry and fallback.
Rate limiter Token bucket and sliding window.
1 / 2

Exercise 1: ATM

Requirements. A customer inserts a card, enters a PIN, withdraws cash and takes the card back. Three wrong PINs lock the card. A withdrawal must be a multiple of 10, within the balance and within a per-transaction limit. The machine holds a limited stock of notes (100, 50, 20, 10) and must refuse a withdrawal it cannot pay exactly.

Design questions. What states does the machine have? Who owns the balance? What happens if the dispenser cannot pay out: is the account debited? (It must not be.) Which part of the design is likely to change? (The way notes are chosen.)

Patterns. State for the session (idle, card inserted, authenticated), and Strategy for the dispensing algorithm. The solution below uses a guard method for states to stay short; you can replace it with state objects as in the vending machine in the previous project.

Exercise 2: Notification service

Requirements. Send a message to a user using their preferred channels in order (for example SMS, then email). Messages come from templates with placeholders. If a channel fails, retry it up to a limit and then fall back to the next channel. Report what happened.

Design questions. Where do channels plug in? Where do templates live? Is retry the channel's job or the service's? How do you test failure?

Patterns. Strategy (one object per channel), a small template renderer, and a chain-like fallback loop. Failure is injected into a fake channel so that the behavior is deterministic.

Solutions 1 and 2

The ATM debits only after the dispenser has produced a plan, so a failed plan changes nothing. The notification service keeps its retry limit as a constructor argument, and the fake channels fail a fixed number of times.

Node.js ATM and notification service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two details deserve attention. In the ATM the note plan is computed and checked before any money or notes move; otherwise a failed payout would leave the books inconsistent. And greedy dispensing is wrong in some inventories (paying 60 with notes 50, 20, 20, 20 fails even though 20 + 20 + 20 works); a real machine would search. In the notification service, the renderer shows a missing placeholder as ? (the last scenario omits order), so a bad template does not crash a send.

Exercise 3: Rate limiter

Requirements. Decide whether a request from a key (user or IP) is allowed. Support a burst but cap the long-run rate. Offer at least two algorithms behind one interface.

Design questions. How do you test code that depends on time? (Inject a clock.) What state is stored per key, and when is it cleaned up? Which algorithm uses less memory? Which one is stricter?

Patterns. Strategy again: allow(key) is the common interface, and token bucket and sliding-window log are two implementations. A real distributed limiter would keep the counters in a shared store; here they live in memory.

Exercise 4: Logger framework

Requirements. Loggers have names such as app.db. Messages have levels (DEBUG, INFO, WARN, ERROR). A logger ignores messages below its level; if it has no level of its own it inherits from the nearest parent. Messages go to one or more appenders (console, file, memory) and are formatted by a formatter.

Design questions. Where does level inheritance live? How can you add a new destination without changing Logger? How do you make output deterministic for tests?

Patterns. Chain of Responsibility-like parent lookup, and Observer or Strategy for appenders and formatters. A manager object owns the registry of loggers.

Solutions 3 and 4

Node.js Rate limiter and logger framework

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The token bucket allows a burst of three and then admits one request per second on average. The sliding window is stricter: it never allows more than three requests in any one-second span, which the printed lines let you compare. The logger shows additive appenders: a message from app.db.pool goes to its own app.db appender and also up to the root appender. That is how most logging frameworks behave, and the reason a level can be inherited while appenders are collected from every ancestor.

Exercise 5: LRU cache

Requirements. A cache with a fixed capacity supports get(key) and put(key, value) in constant time. When it is full, put evicts the least recently used entry. Both get and put count as a use.

Design questions. What two structures give O(1) lookup and O(1) reordering? What are the edge cases: capacity 1, updating an existing key, a miss?

Idea. A hash map from key to node, plus a doubly linked list ordered from most to least recently used. A hit moves the node to the front; eviction removes the tail. See Iterator if you want to make the cache iterable for debugging.

Exercise 6: Tic-tac-toe

Requirements. Two players alternate on an N by N board. The first to fill a row, column or diagonal wins; a full board with no winner is a draw. Reject moves outside the board, on an occupied cell, or after the game has ended.

Design questions. How do you detect a win without scanning the whole board each time? How does the design change for N by N, or for a different winning rule?

Idea. Keep a counter per row, per column and for both diagonals. Each move adds +1 for one player and -1 for the other; a counter reaching N in magnitude means a win. Detection is O(1) per move. The game itself is a tiny state machine: playing, won, draw.

Solutions 5 and 6

Node.js LRU cache and tic-tac-toe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The linked-list version of the LRU cache exists to show the idea behind the structure. In JavaScript you can get the same behavior from a Map, because a Map remembers insertion order: delete the key and set it again to mark a use, and evict the first key. Interviews usually expect the explicit list, because it works in every language. The tic-tac-toe counters make each move constant time and also generalize to larger boards without extra code.

Debrief: patterns across the six

Exercise Core structure Pattern in play Common trap
ATM Session states, dispenser State, Strategy Debiting before the payout is known
Notifications Channels, templates, fallback Strategy, chain of fallbacks Retrying forever, swallowing errors
Rate limiter Per-key counters Strategy Tests that depend on the real clock
Logger Name tree, appenders Chain-like lookup, Observer Forgetting level inheritance
LRU cache Map plus linked list Composition of two structures Forgetting that put of an existing key is a use
Tic-tac-toe Counters per line State machine Scanning the board on every move

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the ATM compute the note plan before debiting the account?

    All checks and the plan come first; the commit that changes balances and notes happens only when everything has succeeded.
  2. 2. Why does the rate limiter receive a clock function instead of calling Date.now() directly?

    Injecting the clock is a form of dependency injection that turns a hidden global into a testable parameter.
  3. 3. In the logger, a message from 'app.db.pool' reached both its own appender and the root appender. Why?

    Levels are inherited from the nearest ancestor; destinations are additive along the name hierarchy.
  4. 4. What two structures make LRU get and put run in constant time?

    The map finds a node in O(1); the doubly linked list can move or remove a node in O(1) once it has the node.
  5. 5. How does the tic-tac-toe solution detect a win without scanning the board?

    Adding +1 for one player and -1 for the other means a full line of one player reaches N or -N.

Summary

  • Every LLD exercise follows the same path: requirements, entities, API, patterns, failure paths, extensions.
  • The ATM and the notification service teach commit-after-check and controlled failure; test failure with fake components.
  • Inject the clock into any time-based design such as a rate limiter, and compare the token bucket (bursty, small state) with the sliding window (strict, more memory).
  • A logger separates names, levels, appenders and formatters; levels are inherited, appenders are additive.
  • An LRU cache is a hash map plus a doubly linked list; eviction removes the tail, and every get or put moves a node to the front.
  • Constant-time win detection with counters is a good example of choosing a data structure that fits the question.

Next lesson: Design Pattern and OOP Interview Questions.