DesignTheSystem/dev
Code Design (LLD) 5 min read

Safe retries with request ids

Make a money operation safe to call twice.

Retries are normal

Networks drop replies. The client cannot tell whether the deposit happened, so it sends it again. Without protection, the money moves twice.

Remember what succeeded

Every request carries an id. Before acting, check whether that id already succeeded; if so, return the stored result. Record the id only after success, so a failed attempt can be retried.

deposit(id: string, amount: number, requestId: string) {
  if (this.done.has(requestId)) return this.done.get(requestId)!;
  const balance = this.apply(id, amount);
  this.done.set(requestId, balance);
  return balance;
}

Key takeaways

  • Assume every call may arrive twice.
  • Check the request id first.
  • Record it only after success.

Hands-on coding exercise

Payments arrive with a key. The same key twice must not charge twice: return the first receipt. The same key with a different amount is a mistake and throws.

interface Receipt {
  id: string;
  amount: number;
}

class Payments {
  /** Charges once per key */
  pay(key: string, amount: number): Receipt {
    throw new Error("Not implemented");
  }

  /** How many real charges were made */
  charges(): number {
    throw new Error("Not implemented");
  }
}

Run your solution against 4 automated tests in the interactive workspace:

Check your understanding

Answer these questions interactively to test what you learned and track progress on your skill map:

  1. When should the request id be recorded?
  2. A retry of a successful deposit should return…

Continue learning