Skip to the content

Lesson 155 of 296

Build: rate limiter, booking clash check, basket with discounts

On this page

These three tasks appear again and again in UK interviews. Each tests a different skill: time-based logic, overlap logic and business rules with money.

Task 1: rate limiter

"Allow each user at most N requests per time window. Return whether a request is allowed."

Why rate limiting matters: it protects APIs from abuse, accidental overload and brute-force login attempts. A limited request usually gets HTTP 429 Too Many Requests.

Questions to ask: Limit per what (user ID, API key, IP address)? Is a burst allowed? Single server or many? What should the response include (for example a Retry-After header)?

Make time injectable. Pass a now function into the class instead of calling Date.now() inside. Then tests can control time without waiting.

Algorithm A: fixed window counter. Count requests per user per window (for example per minute). Simple and cheap, but allows bursts at the window edge: 100 requests at 12:00:59 and 100 more at 12:01:00.

TypeScript
class FixedWindowLimiter {
  private windows = new Map<string, { windowStart: number; count: number }>();

  constructor(
    private limit: number,
    private windowMs: number,
    private now: () => number = Date.now
  ) {}

  allow(key: string): boolean {
    const time = this.now();
    const windowStart = time - (time % this.windowMs);
    const entry = this.windows.get(key);
    if (!entry || entry.windowStart !== windowStart) {
      this.windows.set(key, { windowStart, count: 1 });
      return true;
    }
    if (entry.count < this.limit) {
      entry.count++;
      return true;
    }
    return false;
  }
}

Algorithm B: sliding window log. Keep the timestamps of each user's recent requests. Remove those older than the window; allow if fewer than the limit remain. Accurate, but uses memory per request.

TypeScript
class SlidingWindowLimiter {
  private logs = new Map<string, number[]>();

  constructor(
    private limit: number,
    private windowMs: number,
    private now: () => number = Date.now
  ) {}

  allow(key: string): boolean {
    const time = this.now();
    const cutoff = time - this.windowMs;
    const recent = (this.logs.get(key) ?? []).filter((t) => t > cutoff);
    if (recent.length >= this.limit) {
      this.logs.set(key, recent);
      return false;
    }
    recent.push(time);
    this.logs.set(key, recent);
    return true;
  }
}

Algorithm C: token bucket. Each user has a bucket holding up to capacity tokens. Tokens refill at a steady rate. Each request spends one token; with no tokens, it is refused. Allows short bursts while keeping a steady average rate. Widely used in API gateways.

TypeScript
class TokenBucketLimiter {
  private buckets = new Map<string, { tokens: number; lastRefill: number }>();

  constructor(
    private capacity: number,
    private refillPerSecond: number,
    private now: () => number = Date.now
  ) {}

  allow(key: string): boolean {
    const time = this.now();
    const bucket = this.buckets.get(key) ?? { tokens: this.capacity, lastRefill: time };
    const elapsedSeconds = (time - bucket.lastRefill) / 1000;
    bucket.tokens = Math.min(this.capacity, bucket.tokens + elapsedSeconds * this.refillPerSecond);
    bucket.lastRefill = time;
    if (bucket.tokens >= 1) {
      bucket.tokens -= 1;
      this.buckets.set(key, bucket);
      return true;
    }
    this.buckets.set(key, bucket);
    return false;
  }
}
AlgorithmAccuracyMemory per userBursts
Fixed windowEdge bursts possibleO(1)Up to 2× the limit at window edges
Sliding window logExactO(limit)None beyond the limit
Token bucketSmooth averageO(1)Allowed up to the capacity

What to mention: with several servers, in-memory limits are per server; use a shared store such as Redis (Part 15). Old keys should be cleaned up to avoid memory leaks. Respond with 429 and a Retry-After header.

Task 2: booking clash check

"Rooms (or instructors, or tables) are booked for time ranges. Reject a new booking that overlaps an existing one for the same room."

Questions to ask: Can a booking start exactly when another ends? (Usually yes.) Are times in UTC? What about cancelled bookings? Are there opening hours or minimum lengths?

The overlap rule (Lesson 144): two bookings overlap when newStart < existingEnd && existingStart < newEnd. With strict <, back-to-back bookings (10:00 to 11:00, then 11:00 to 12:00) are allowed.

TypeScript
type Booking = {
  id: string;
  roomId: string;
  start: Date;
  end: Date;
  cancelled?: boolean;
};

class BookingClashError extends Error {
  constructor(public clashWith: string) {
    super(`Booking clashes with ${clashWith}`);
    this.name = "BookingClashError";
  }
}

class BookingService {
  private bookingsByRoom = new Map<string, Booking[]>();
  private nextId = 1;

  book(roomId: string, start: Date, end: Date): Booking {
    if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
      throw new ValidationError("start and end must be valid dates");
    }
    if (start >= end) throw new ValidationError("start must be before end");

    const existing = this.bookingsByRoom.get(roomId) ?? [];
    const clash = existing.find(
      (b) => !b.cancelled && start < b.end && b.start < end
    );
    if (clash) throw new BookingClashError(clash.id);

    const booking: Booking = { id: `B${this.nextId++}`, roomId, start, end };
    existing.push(booking);
    this.bookingsByRoom.set(roomId, existing);
    return booking;
  }

  cancel(id: string): void {
    for (const list of this.bookingsByRoom.values()) {
      const booking = list.find((b) => b.id === id);
      if (booking) {
        booking.cancelled = true;
        return;
      }
    }
    throw new NotFoundError("Booking", id);
  }
}
  • Validates dates and that start < end.
  • Groups bookings by room, so only relevant bookings are checked.
  • Cancelled bookings are kept (for history) but ignored in clash checks. This is a soft delete (Part 17).
  • Checking is O(k) for k bookings in that room. For many bookings, keep them sorted by start and binary search (O(log k)).

The concurrency problem: the follow-up that matters most. Two users submit overlapping bookings at the same moment on two servers. Both checks pass, because neither booking is saved yet, and you get a double booking. An in-memory check cannot prevent this across servers. Real solutions (Part 17):

  • A database transaction with row locking.
  • A database constraint: PostgreSQL can enforce "no overlapping ranges for the same room" with an exclusion constraint, which is the strongest guarantee.
  • A unique constraint on fixed time slots, if bookings use fixed slots.

Mentioning this unprompted is a strong signal of seniority.

Task 3: shopping basket with discounts

"Products have prices. Calculate a basket total with these offers: buy one get one free on some products, 3 for £10 on others, and a 10% discount code on the whole basket."

Questions to ask: In what order are discounts applied? Can several apply to one item? Does the percentage code apply before or after the multi-buy offers? How should rounding work? Is VAT included in prices?

Design: keep each offer as a separate small function (the strategy pattern, Part 21), so new offers can be added without changing existing code.

TypeScript
type Product = { sku: string; name: string; pricePence: number };
type BasketLine = { product: Product; quantity: number };

type Offer = {
  description: string;
  appliesTo: (sku: string) => boolean;
  discountFor: (line: BasketLine) => number;
};

function buyOneGetOneFree(skus: string[]): Offer {
  return {
    description: "Buy one get one free",
    appliesTo: (sku) => skus.includes(sku),
    discountFor: ({ product, quantity }) => Math.floor(quantity / 2) * product.pricePence
  };
}

function multiBuy(skus: string[], groupSize: number, groupPricePence: number): Offer {
  return {
    description: `${groupSize} for £${(groupPricePence / 100).toFixed(2)}`,
    appliesTo: (sku) => skus.includes(sku),
    discountFor: ({ product, quantity }) => {
      const groups = Math.floor(quantity / groupSize);
      const saving = groupSize * product.pricePence - groupPricePence;
      return groups * Math.max(0, saving);
    }
  };
}

type BasketTotal = {
  subtotalPence: number;
  offerDiscountPence: number;
  codeDiscountPence: number;
  totalPence: number;
};

function priceBasket(lines: BasketLine[], offers: Offer[], percentCode = 0): BasketTotal {
  if (percentCode < 0 || percentCode > 100) throw new ValidationError("invalid discount percentage");
  let subtotalPence = 0;
  let offerDiscountPence = 0;

  for (const line of lines) {
    if (!Number.isInteger(line.quantity) || line.quantity < 0) {
      throw new ValidationError(`invalid quantity for ${line.product.sku}`);
    }
    subtotalPence += line.product.pricePence * line.quantity;
    const best = offers
      .filter((o) => o.appliesTo(line.product.sku))
      .reduce((max, o) => Math.max(max, o.discountFor(line)), 0);
    offerDiscountPence += best;
  }

  const afterOffers = subtotalPence - offerDiscountPence;
  const codeDiscountPence = Math.round((afterOffers * percentCode) / 100);
  return {
    subtotalPence,
    offerDiscountPence,
    codeDiscountPence,
    totalPence: afterOffers - codeDiscountPence
  };
}

Decisions to state clearly (and confirm with the interviewer):

  • All money is in integer pence; rounding happens once, on the code discount.
  • If several offers apply to one product, the best one is used, not all of them.
  • Multi-buy offers never give a negative saving (Math.max(0, ...)) if the group price is higher than buying separately.
  • The percentage code applies after product offers.
  • The result shows each part separately, which is what a receipt needs, and makes testing easier.

Example: coffee £3.50 with BOGOF, quantity 3; cookies £4.00 with "3 for £10", quantity 4; 10% code.

StepPence
Subtotal3 × 350 + 4 × 400 = 2,650
BOGOF saving1 free coffee = 350
3 for £10 savingone group: 1,200 − 1,000 = 200
After offers2,100
10% code210
Total1,890 (£18.90)

How to say it in an interview

"For the rate limiter I inject the clock so it is testable, and compare fixed window, sliding log and token bucket; across several servers I'd keep counters in Redis and return 429 with Retry-After. For booking clashes I use the overlap rule start before other end and other start before end, ignore cancelled bookings, and point out that a real system must enforce it in the database with a transaction or an exclusion constraint to prevent race conditions. For the basket I keep money in pence, model each offer as a separate strategy, apply the best offer per line, apply the percentage code after offers with a single rounding, and return each component for the receipt."

Key words

WordMeaning
Rate limiterLimits how many requests a client can make in a period
429 Too Many RequestsThe status code for rate-limited requests
Token bucketA limiter where requests spend tokens that refill over time
Injectable clockPassing a time function in so tests can control time
Race conditionA bug when two operations happen at the same time
Exclusion constraintA database rule that stops overlapping ranges
Strategy patternSeparate interchangeable functions for each rule

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.