Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Practice and Review

Practice Exercises with Solutions

Twelve graded microservices exercises on boundaries, messaging, sagas and resilience, each with a runnable Node solution and notes on what to check.

Reading about microservices only gets you so far. The ideas stick when you build the small mechanisms yourself: a duplicate-safe consumer, a compensating saga, a circuit breaker. This page has twelve exercises in four groups, from easy to harder, each with a runnable solution.

How to use it: read the exercise, close your eyes on the code below it, and write your own version in the editor first (change the starting code, or start from an empty file). Then run the provided solution and compare. If your output differs, work out why before reading the solution line by line.

Everything here runs in one Node process, so the "services" are objects and functions and time is faked where timing matters. That keeps the output exactly repeatable, but it also means the real difficulties of a network (slow replies, partial failure, ordering) are only modelled, not experienced. The earlier lessons discuss those honestly; these exercises train the logic.

Twelve exercises, four groups

Boundaries Ownership, coupling, routing.
Messaging Duplicates, fan-out, dead letters.
Sagas Compensation, outbox.
Resilience Backoff, breaker, limiter.

Difficulty rises inside each group.

1 / 2

Group 1: Boundaries

These three exercises use the ideas from Finding Boundaries with Domain-Driven Design, Decomposition Strategies and Database per Service and Data Ownership.

Exercise 1 (easy): ownership violations. You get a list of which service reads or writes which table. Report every table written by more than one service, and every table read directly by a service that does not write it.

Exercise 2 (easy): merge candidates. You get the number of calls one user request causes between pairs of services (in either direction). Find the pair that talks the most and say whether it should be merged.

Exercise 3 (medium): stable percentage routing. Write useNew(userId, percent) for a strangler facade. It must be deterministic: the same user always gets the same answer for the same percentage, and everyone at 10 percent must also be included at 50 percent.

Node.js Solutions 1 to 3

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.

What to check in your own version: Exercise 1 must catch the shipping write to orders (two owners) and the billing read; Exercise 2 sums both directions before comparing; Exercise 3 works because a user's hash number never changes, only the threshold does. The group sizes (about 10 and 50 percent) are close to, but not exactly, the requested share, because hashes spread users only approximately evenly.

Group 2: Messaging

These exercises practise Asynchronous Messaging and Events and the delivery guarantees behind them.

Exercise 4 (easy): duplicate-safe consumer. Messages can arrive more than once (at-least-once delivery). Build a consumer that applies each message id exactly once, but does not remember an id if the handler failed, so a redelivery can try again.

Exercise 5 (medium): topics and fan-out. Write a tiny in-memory broker with subscribe(topic, handler) (returning an unsubscribe function) and publish(topic, message) (returning how many handlers received it).

Exercise 6 (medium): dead-letter queue. Process a list of messages with a handler that sometimes throws. Retry each message up to three attempts. A message that still fails goes to a dead-letter list together with its last error.

Node.js Solutions 4 to 6

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.

What to check: in Exercise 4 the id is added to seen only after handler returns. Recording it first would turn a failed attempt into a lost message. In Exercise 6, message 3 succeeds on its third attempt and message 2, which can never succeed, ends up in the dead-letter list for a human or a repair job. Sending it there quickly protects the rest of the queue (Project: Event-Driven Notification System builds this at larger scale).

Group 3: Sagas and the outbox

These use Sagas and The Transactional Outbox and Idempotent Consumers.

Exercise 7 (medium): a saga runner. Write runSaga(steps). Each step has run and undo. Run the steps in order. If one fails, undo the completed steps in reverse order and report where it failed. Do not undo the failed step itself.

Exercise 8 (medium): the order saga. Use your runner for an order with three steps: reserve stock, charge payment, create shipment. Payments over 500 are declined. Show a successful order, then a declined one, and print the stock afterwards.

Exercise 9 (harder): outbox. Write placeOrder so that the order row and an OrderPlaced outbox row are saved in one atomic step, and a failure saves neither. Then write a relay that publishes unpublished outbox rows and marks them, so running it twice never publishes a row twice.

Node.js Solutions 7 to 9

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.

What to check: in Exercise 7 the undo list is built from completed, so the failed step is never undone, and the undo order is the reverse of the run order. In Exercise 9, a crash between publish(row) and row.published = true would publish twice on the next run. That is why real consumers must still be idempotent (Exercise 4): the outbox gives at-least-once delivery, not exactly-once.

Group 4: Resilience

These use Timeouts, Retries and Exponential Backoff, Circuit Breakers, Bulkheads and Fallbacks and Rate Limiting, Load Shedding and Backpressure. Time is faked: functions receive a clock or a sleep that records the wait instead of waiting.

Exercise 10 (medium): retry with backoff. Write retry(fn) with up to 5 attempts and delays of 100, 200, 400, 800 ms (doubling, capped at 1000). Record the delays and return the successful result, or throw the last error.

Exercise 11 (harder): circuit breaker. After 3 consecutive failures the breaker opens and rejects calls immediately. After a 1000 ms cool-down the next call is allowed through as a trial (half-open): success closes the breaker, failure opens it again.

Exercise 12 (harder): token bucket. A bucket holds up to 3 tokens and refills at 1 token per second. take() returns true and uses a token, or false when none is left. Use an injected clock.

Node.js Solutions 10 to 12

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.

What to check: the breaker counts only consecutive failures (a success resets the count), a half-open trial that fails reopens it at once, and the bucket never stores more than its capacity, so a long pause allows a burst of three, not sixty. Real libraries add jitter to backoff, sliding windows to breakers and shared storage to limiters; the logic you wrote is the core.

Stretch goals: add random "full jitter" to Exercise 10 and show the spread of delays; make the breaker in Exercise 11 open on an error rate over a window instead of a count; make the bucket in Exercise 12 keyed by user id so each user has their own.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Exercise 4, why is the message id recorded only after the handler succeeds?

    If the id were recorded first, a handler failure would make the redelivery look like a duplicate and the message would be lost.
  2. 2. In a saga, which steps are compensated when step 3 of 4 fails?

    Only completed steps need undoing, newest first. The failed step did not complete and step 4 never ran.
  3. 3. Why can the outbox relay still publish a row twice after a crash?

    Publishing and marking are separate steps. The outbox guarantees at-least-once delivery, so consumers must be idempotent.
  4. 4. What does a half-open circuit breaker do?

    Half-open is the probing state after the cool-down: one trial decides whether the dependency has recovered.
  5. 5. Why does a token bucket cap the number of stored tokens at its capacity?

    The capacity is the maximum burst. Without a cap, a minute of silence would allow sixty requests at once.

Summary

  • Twelve exercises covered ownership checks, merge candidates, stable routing, idempotent consumers, a broker, dead letters, a saga runner, an outbox, retries, a circuit breaker and a token bucket.
  • Make state changes safe to repeat and safe to undo: idempotent handlers, compensations in reverse order, recorded-after-success ids.
  • The outbox and retries give at-least-once delivery, so duplicate handling is always part of the design.
  • Faking time with an injected clock makes timing logic testable and repeatable.
  • Re-do any exercise from an empty file a week later; that is the best test of whether the idea stuck.

Next: Microservices Interview Questions.