LLD

Full Designs

Car Rental

A weak answer counts cars per branch and charges a card. We build one that holds up when the interviewer pushes: how a one-way trip moves a car to another branch, why a booking holds one specific car, what happens when two customers want the same car at once, how a deposit is held at pickup and taken at return, and how a late, low-fuel return is billed to the cent.

"Design a car rental system" sounds like the hotel question with cars instead of rooms. A weak answer keeps a count of cars per branch per day, books against the count, and charges the card. The classes look right, and the parts that make car rental its own problem are still open.

The interviewer is checking a few specific things. A car rented one way from San Francisco (SFO) to Los Angeles (LAX) is in Los Angeles afterwards, so the cars a branch can offer depend on cars arriving from other branches. A returned car needs time to be inspected before the next customer gets it. The card is not charged when booking: a deposit is held at pickup, and the final amount is taken at return, after late hours, missing fuel and extra miles are added. And two customers can ask for the same car at the same moment.

This article follows a 45 minute interview. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

A rental at a glance
Asha's phone asks RentalService to book an SUV from SFO to LAX (1). book() finds a car whose CarSchedule is free for the trip, has the car at SFO when it starts, and still lets it reach its next trip (2). At the SFO counter, pickUp() (3) asks CardGateway to hold $567.00 on her card (4). At the LAX counter, returnCar() (5) asks the list of ChargeRules for the bill, $424.75 in all (6), and captures that much from the hold (7).Asha's phone asks RentalService to book an SUV from SFO to LAX (1). book() finds a car whose CarSchedule is free for the trip, has the car at SFO when it starts, and still lets it reach its next trip (2). At the SFO counter, pickUp() (3) asks CardGateway to hold $567.00 on her card (4). At the LAX counter, returnCar() (5) asks the list of ChargeRules for the bill, $424.75 in all (6), and captures that much from the hold (7).
A booking takes one car's time. The card is held at pickup, and the bill is taken from the hold at return. Asha's phone asks RentalService to book an SUV from SFO to LAX (1). book() finds a car whose CarSchedule is free for the trip, has the car at SFO when it starts, and still lets it reach its next trip (2). At the SFO counter, pickUp() (3) asks CardGateway to hold $567.00 on her card (4). At the LAX counter, returnCar() (5) asks the list of ChargeRules for the bill, $424.75 in all (6), and captures that much from the hold (7).

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
Does a customer book a car or a class of car?A class, such as SUV. We pick a specific car when bookingOne schedule per car, and book tries the cars of the class
Can a car be returned to another branch?Yes, between any two branches, if it was booked that wayEvery booking has a pickup and a return branch, and a car's place changes
How is time measured?Whole hours. A trip is 1 hour to 30 days, picked up within 365 daysChecks in Trip and in book
How is a trip priced?A daily rate per class. Every started 24 hours is a dayTrip.priceCents, worked out when booking
When is the card used?A hold at pickup for the price plus a deposit. The final bill is taken from the hold at returnA CardGateway with authorise, capture and release
What is added at return?Late hours after 30 minutes of grace, missing fuel, miles over 200 a day, and damage up to a $1,000 excessA list of ChargeRules
How long between two rentals of one car?2 hours, to inspect and clean itEvery rental blocks its car for 2 hours after it ends
Can a car go out of service?Yes, for a period staff choose, unless a booking is in the wayA maintenance block in the car's schedule
Do many customers book at once?Yes, often for the same few carsBooking must be safe from many threads

The second question matters most. If every car comes back to its own branch, each branch has a fixed set of cars, and the design is close to Hotel Booking: a count per class per day. One-way trips break that. A car's branch changes with every one-way trip, so whether SFO has an SUV on Friday depends on which trips end at SFO before Friday, and which start there after it.

Requirements

Functional:

  1. A customer books a class of car, from a branch at a time, to a branch at a time. The booking gets one specific car. That car is at the pickup branch then, is free for the trip and the 2 hours after it, and can still reach the start of its next booking. If no car fits, the booking is refused.
  2. A customer can cancel before pickup. Later bookings of the same car keep it.
  3. At pickup, the card is held for the price plus the class's deposit. If the card is declined, the rental stays booked and the car stays at the branch.
  4. At return, the final bill is the price plus late hours, missing fuel, extra miles and damage, exact to the cent. The bill is taken from the hold and the rest of the hold is released. Anything above the hold is recorded as owed.
  5. Staff can take a car out of service for a period, unless a booking is in the way.
  6. No car is ever booked for two overlapping periods, or from a branch it will not be at.

Out of scope: choosing a model, returning to a branch other than the one booked, giving the next customer another car after a late return, refunds for early returns, insurance, taxes, and search. We come back to these at the end, because each is a likely follow-up.

Everything lives in memory, as is normal for a low-level design interview.

What the code itself must handle:

  • Many bookings at once. book and cancel are called from many threads, often for the same car.
  • A bank that fails. The card processor can decline, or not answer, on a hold or a capture. A call that is repeated must never hold or take money twice.
  • Rules that change. The charges added at return sit behind an interface.
  • Testable time. Pickup windows and late fees depend on the time, so the service takes a Clock.

Finding the classes

Picking the nouns out of the requirements gives a first list. Two of them hold state that changes and that several threads touch: a car's bookings and a rental. They become the classes CarSchedule and Rental, and RentalService coordinates them. The extra charges and the card processor become interfaces.

From nouns to classes
RentalService, CarSchedule and Rental become classes. Car, branch, trip, a stretch of a car's time, a reading of fuel and miles, and the bill become records, and the car class becomes an enum. The extra charge and the card hold become interfaces. Six nouns are dropped. A customer is a name on the rental. A counter agent is a caller of RentalService. A branch keeps no list of cars. The deposit is a number on CarClass. Inspection is two hours after every rental. Keys are hardware.RentalService, CarSchedule and Rental become classes. Car, branch, trip, a stretch of a car's time, a reading of fuel and miles, and the bill become records, and the car class becomes an enum. The extra charge and the card hold become interfaces. Six nouns are dropped. A customer is a name on the rental. A counter agent is a caller of RentalService. A branch keeps no list of cars. The deposit is a number on CarClass. Inspection is two hours after every rental. Keys are hardware.
Most nouns become classes, records or interfaces. Six do not. RentalService, CarSchedule and Rental become classes. Car, branch, trip, a stretch of a car's time, a reading of fuel and miles, and the bill become records, and the car class becomes an enum. The extra charge and the card hold become interfaces. Six nouns are dropped. A customer is a name on the rental. A counter agent is a caller of RentalService. A branch keeps no list of cars. The deposit is a number on CarClass. Inspection is two hours after every rental. Keys are hardware.
Decision

Should a branch keep a list of its cars?

Yes: each branch holds the cars parked there

It mirrors the car park. But a one-way trip moves a car between two lists, and a booking for next week needs next week's list. The lists would be a second record of where each car is, kept in step by hand.

No: a car's place comes from its own scheduleOur pick

Every booking of a car says where it starts and where it ends. The car is wherever its last booking before that time ended, or where it started if there is none. Branch is a record with a code, and RentalService keeps the set of branches only to refuse unknown ones.

Data or behaviour?

Values that never change, such as a car, a trip or a bill, are records, whose fields are fixed when they are created. CarSchedule and Rental are ordinary classes, because their state changes under a lock.

The class diagram

The classes and how they connect
RentalService owns one CarSchedule per car and every Rental. It uses two interfaces, ChargeRule and CardGateway, and reads the time from a Clock. The note under ChargeRule names its four classes. Methods marked ~ are package-private, and only the rental package calls them. The records and enums along the bottom are the values the classes above hold. The three exceptions are not drawn.RentalService owns one CarSchedule per car and every Rental. It uses two interfaces, ChargeRule and CardGateway, and reads the time from a Clock. The note under ChargeRule names its four classes. Methods marked ~ are package-private, and only the rental package calls them. The records and enums along the bottom are the values the classes above hold. The three exceptions are not drawn.
RentalService coordinates. Each car's schedule and each rental has its own lock. RentalService owns one CarSchedule per car and every Rental. It uses two interfaces, ChargeRule and CardGateway, and reads the time from a Clock. The note under ChargeRule names its four classes. Methods marked ~ are package-private, and only the rental package calls them. The records and enums along the bottom are the values the classes above hold. The three exceptions are not drawn.

The classes fall into three groups:

  • Data: the records Car, Branch, Trip, Block, Reading, ReturnFacts, Bill and BillLine, and the enums CarClass, RentalStatus, Block.Kind and CaptureResult.
  • The core: RentalService, CarSchedule and Rental. RentalService coordinates. The other two each guard their own state with their own lock.
  • Rules and outside systems: ChargeRule and CardGateway, both interfaces.

Refusals that a person should read, such as no car for a trip or a declined card, are a NotAllowedException or one of its two subclasses, with the reason in the message. A null, a bad reading or an overflowing total is a bug in the calling code, so it throws IllegalArgumentException, NullPointerException or ArithmeticException. A rule that breaks its own contract throws IllegalStateException.

Building it

What a booking holds

A customer asks for an SUV, not for SUV-1. The design still has to decide whether the booking holds the class or one car.

Decision

Does a booking hold a specific car or a class of car?

A class, with a count per branch per day, and a car given out at pickup

This is the Hotel Booking answer, and it lets any free car serve any booking. But a one-way trip takes a car out of one branch's count and adds it to another's from the return time on, and a cancel must undo both. The counts would also have to prove that a real car will be standing there, which means following each car anyway.

A specific car, chosen when bookingOur pick

Each car has one schedule, and a booking is a stretch of it. Whether the car is free, and where it will be, are both read from that one schedule. The cost is the one the hotel page shows: fixed assignments can refuse a trip that moving other bookings between cars would fit.

A trip carries the class, both branches and both times. Its constructor refuses times that are not on the hour, a return before the pickup, and a trip over 30 days. The price is the daily rate times the started days:

trip/Trip.javalines 37–45 of 50
    /** Every started 24 hours is a full day. */    public long days() {        long hours = Duration.between(pickupAt, returnAt).toHours();        return (hours + HOURS_PER_DAY - 1) / HOURS_PER_DAY;    }     public long priceCents() {        return Math.multiplyExact(carClass.dailyRateCents(), days());    }

Asha's trip from Monday 09:00 to Thursday 09:00 is 72 hours, so 3 days of SUV at $89.00 is $267.00.

One car's schedule

A Block is one stretch of a car's time: an id, a kind, a start and an end, the branch the car leaves from, and the branch it ends at. A rental is a block. So is a staff transfer, and so is time in the workshop. CarSchedule keeps one car's blocks in a TreeMap by start time, and adding a block runs four checks:

rental/CarSchedule.javalines 130–148 of 149
    // Blocks never overlap, so only the two neighbours of a new block can clash with it.    private Optional<String> problemWith(Block block) {        Map.Entry<Instant, Block> before = byStart.floorEntry(block.start());        Map.Entry<Instant, Block> after = byStart.higherEntry(block.start());        if (before != null && before.getValue().readyAt().isAfter(block.start())) {            return Optional.of("busy with " + before.getValue().id() + " until " + before.getValue().readyAt());        }        if (after != null && block.readyAt().isAfter(after.getKey())) {            return Optional.of("busy with " + after.getValue().id() + " from " + after.getKey());        }        Branch here = before == null ? car.startsAt() : before.getValue().to();        if (!here.equals(block.from())) {            return Optional.of("it will be at " + here + ", not " + block.from());        }        if (after != null && !block.to().equals(after.getValue().from())) {            return Optional.of(after.getValue().id() + " needs it at " + after.getValue().from());        }        return Optional.empty();    }

The time checks (lines 134 to 139) follow the Meeting Room Scheduler. Blocks never overlap, so only the two neighbours of a new block can clash with it. floorEntry finds the block that starts at or before the new one, and higherEntry finds the first block after it. That page uses ceilingEntry for the second lookup. Both pages agree, because a block with the same start is already found by floorEntry. The place checks use the same two neighbours:

  1. The car must be at the pickup branch (line 140). It is where the block before ended, or at startsAt if there is none.
  2. The car must reach its next block (line 144). The new block must end where the next one starts. Otherwise a one-way trip put in before a booking would leave that booking with no car.

Two neighbours are enough because every block starts where the one before it ended. The blocks form a chain of branches. A new block keeps the chain whole if it starts where the block before ends and ends where the block after starts, and no block further away notices.

Where a car will be
SUV-1 has one booking, R-1: Asha takes it from SFO on Monday 09:00 to LAX on Thursday 09:00. The amber strip is the two hours of inspection after it. Dev's trip from SFO to LAX on Sunday fits in time, but it would leave the car at LAX, and R-1 needs it at SFO on Monday, so it is refused. Chen's round trip from LAX starts on Thursday 10:00, while the car is still being inspected, so it is refused. Ben's trip from LAX on Friday fits.SUV-1 has one booking, R-1: Asha takes it from SFO on Monday 09:00 to LAX on Thursday 09:00. The amber strip is the two hours of inspection after it. Dev's trip from SFO to LAX on Sunday fits in time, but it would leave the car at LAX, and R-1 needs it at SFO on Monday, so it is refused. Chen's round trip from LAX starts on Thursday 10:00, while the car is still being inspected, so it is refused. Ben's trip from LAX on Friday fits.
A trip must fit in time, start where the car is, and leave the car where its next trip starts. SUV-1 has one booking, R-1: Asha takes it from SFO on Monday 09:00 to LAX on Thursday 09:00. The amber strip is the two hours of inspection after it. Dev's trip from SFO to LAX on Sunday fits in time, but it would leave the car at LAX, and R-1 needs it at SFO on Monday, so it is refused. Chen's round trip from LAX starts on Thursday 10:00, while the car is still being inspected, so it is refused. Ben's trip from LAX on Friday fits.
Decision

How do we know where a car will be?

A location field on Car, updated at pickup and return

It shows where the car is now. But bookings are about next week, and the field cannot say where the car will be then, after trips that have not happened yet.

Read it from the schedule: the block before ends where the car isOur pick

The schedule already holds every future move, so the answer for any time is one floorEntry, which whereAt uses. Checking a new block costs two lookups of O(log n) for a car with n blocks. The cost is that every change must keep the chain whole, which is why cancelling needs care.

The two hours of inspection come from the block itself:

rental/Block.javalines 33–36 of 41
    /** When the car can start its next block. */    public Instant readyAt() {        return kind == Kind.MAINTENANCE ? end : end.plus(TURNAROUND);    }
Decision

How does a returned car get time for inspection?

An inspection block, added when the car comes back

It records the real work. But later bookings were made long before the return, and if the next pickup is 30 minutes after it, there is no room left.

A fixed two hours after every rental, in readyAt()Our pick

Every booking leaves two hours free after the one before it, so the time exists before anyone needs it. After maintenance the car is ready at once. A late return eats into the two hours, which is a follow-up.

Cancelling a one-way trip

Removing a block can break the chain. In the demo, Dev books SUV-2 from SFO to LAX on Sunday, and Ed books it at LAX on Tuesday. If Dev cancels and his block is removed, SUV-2 stays at SFO, and Ed's booking points at a car that will not be there.

rental/CarSchedule.javalines 60–103 of 149
    /** Cancels a block. The car still makes the move unless no later block needs it. */    synchronized void cancel(String blockId, Instant now) {        Instant start = startById.get(blockId);        if (start == null) {            throw new IllegalStateException(car.id() + " has no block " + blockId);        }        Block block = byStart.get(start);        if (block.from().equals(block.to())) {            // Only a booked rental is cancelled, and a round trip that never began never moves the car.            byStart.remove(start);            startById.remove(blockId);        } else {            byStart.put(start, block.asTransfer());        }        dropUnneededTransfers(blockId, now);    }     // A run of transfers is needed only if the next block starts somewhere other than where the run begins.    // A transfer that started before this cancel is fixed: the car has moved.    private void dropUnneededTransfers(String cancelledId, Instant now) {        List<Block> run = new ArrayList<>();        Branch beforeRun = car.startsAt();        for (Block block : new ArrayList<>(byStart.values())) {            boolean movable = block.kind() == Block.Kind.TRANSFER                    && (block.start().isAfter(now) || block.id().equals(cancelledId));            if (movable) {                run.add(block);                continue;            }            if (beforeRun.equals(block.from())) {                removeAll(run);            }            run.clear();            beforeRun = block.to();        }        removeAll(run);    }     private void removeAll(List<Block> blocks) {        for (Block block : blocks) {            byStart.remove(block.start());            startById.remove(block.id());        }    }

A cancelled round trip never moves the car, so cancel removes it at once. A one-way trip becomes a TRANSFER: staff drive the car to LAX at the same times. Then dropUnneededTransfers walks the chain and removes every run of transfers that nobody needs. A run is needed only if the block after it, a booking or maintenance, starts somewhere other than where the run begins. A run at the end of the chain moves the car for nobody, so it goes too. A transfer that started before this cancel stays, because the car has moved. Dev's transfer stays, because Ed starts at LAX.

Decision

A cancelled one-way trip leaves a later booking without a car. What now?

Remove the block, and move the later booking to another car

No other car may be at LAX on Tuesday, and a moved booking can strand the booking after it in turn. Ed could lose his booking because Dev changed his plans.

Refuse the cancel

The chain stays whole, but a customer cannot cancel a trip because of someone else's booking.

Keep the move as a staff transferOur pick

The car still reaches LAX, so every later booking stands. If Ed cancels before Sunday, the transfer goes, because nobody needs the car at LAX. Two transfers in a row that end where they began, such as SFO to LAX and back, go as well. The cost is a driver's time, and the car is blocked for the whole of Dev's booked trip, which is longer than the drive.

Two customers, one car

Ann wants an SUV from SFO to LAX on Monday. Bo wants one for an SFO round trip on Tuesday. Both requests arrive at the same moment, and both try SUV-1 first. Each trip fits on its own. Together they do not: after Ann's trip the car is at LAX, so Bo's Tuesday pickup at SFO would have no car.

Two customers, one car
On the left there is no lock. Ann checks SUV-1 and her trip fits. Bo checks before Ann adds hers, and his fits too. Both add their blocks, so Bo's Tuesday pickup is at SFO while the car is in LAX. On the right, tryAdd() holds SUV-1's lock. Ann checks and adds in one step. Bo waits, finds that the car will be at LAX, and is refused, so book() tries SUV-2.On the left there is no lock. Ann checks SUV-1 and her trip fits. Bo checks before Ann adds hers, and his fits too. Both add their blocks, so Bo's Tuesday pickup is at SFO while the car is in LAX. On the right, tryAdd() holds SUV-1's lock. Ann checks and adds in one step. Bo waits, finds that the car will be at LAX, and is refused, so book() tries SUV-2.
Without a lock, both requests can check SUV-1 before either adds its block. On the left there is no lock. Ann checks SUV-1 and her trip fits. Bo checks before Ann adds hers, and his fits too. Both add their blocks, so Bo's Tuesday pickup is at SFO while the car is in LAX. On the right, tryAdd() holds SUV-1's lock. Ann checks and adds in one step. Bo waits, finds that the car will be at LAX, and is refused, so book() tries SUV-2.

The design keeps this safe in one place. tryAdd is synchronized on the car's schedule, so checking the neighbours and adding the block happen as one step:

rental/CarSchedule.javalines 34–42 of 149
    /** Adds the block if the car is free then, is at its pickup branch, and still reaches its next block. */    synchronized boolean tryAdd(Block block) {        if (problemWith(block).isPresent()) {            return false;        }        byStart.put(block.start(), block);        startById.put(block.id(), block.start());        return true;    }

book works out the price first, then tries each car of the class in turn until one accepts the block:

rental/RentalService.javalines 83–93 of 316
        long price = trip.priceCents();        String id = "R-" + nextRentalId.getAndIncrement();        Block block = blockFor(id, trip);        for (CarSchedule schedule : schedulesByClass.getOrDefault(trip.carClass(), List.of())) {            if (schedule.tryAdd(block)) {                Rental rental = new Rental(id, customer, schedule.car(), trip, price);                rentals.put(id, rental);                return rental;            }        }        throw new NoCarException(trip);

The project includes a check, demo/RaceCheck.java. It sends 1,000 requests at 4 SUVs that start at SFO, through 16 threads that a latch releases together. A third of the requests are Ann's Monday trip and a third are Bo's Tuesday trip. The rest are a Wednesday trip from LAX, which fits only a car that went to LAX on Monday:

$ java demo.RaceCheck
1,000 customers, 16 threads, 4 SUVs that start at SFO
Trips: SFO to LAX on Monday, SFO round trip on Tuesday, LAX to SFO on Wednesday
Cars holding exactly one Monday or Tuesday trip: 4 of 4
Bookings that start where the car is not: 0
Bookings that overlap the one before on the same car: 0
Rentals missing from their car's schedule: 0

Each car holds one of the early trips, never both, and every booking starts where its car is. We also ran it in a scratch copy with synchronized removed from tryAdd. Every run broke in at least one of these ways. Fewer than 4 cars held exactly one early trip. Some bookings started where the car would not be. Some customers held rentals that their car's schedule did not list. That last one happens when two of them get the same car for the same hours, and one block replaces the other in the map.

Decision

Where do the locks go?

One lock around all of book and cancel

It is correct and easy to explain. But every booking in the company would wait for every other one, even for cars in different cities.

One lock per car's schedule, held only while checking and addingOur pick

A car's blocks are the only state a booking changes in several steps, so they share one lock. Two bookings wait for each other only while they try the same car, for a few map operations. Bookings of one class try the cars in the same order, so they do queue briefly on the first car. Each Rental guards its status with its own lock, and no lock is held during a bank call.

Pickup and the hold

A rental company does not charge the card when booking. At pickup it asks the bank to hold an amount: the money stays in the customer's account, but it cannot be spent. At return it captures the final bill from the hold, and the bank releases the rest.

payment/CardGateway.javalines 3–18 of 18
/** * The card processor, outside our code. Every call carries a hold key, and the processor * promises: a second authorise with the same key returns the first answer and holds nothing more; * a second capture with the same key returns the first answer and takes nothing more; * release with no hold does nothing. A hold lapses after a period the card network sets, * which for car rental can be about a month. */public interface CardGateway {    /** True if the hold is placed, false if declined. Throws if no answer comes back. */    boolean authorise(String holdKey, String cardToken, long amountCents);     /** Takes this much of the hold and releases the rest, or refuses for good. Throws if no answer comes back. */    CaptureResult capture(String holdKey, long amountCents);     void release(String holdKey);}

Every call carries a hold key, and the bank's promises are about keys. A second authorise with the same key returns the first answer and holds nothing more. A second capture with the same key returns the first answer and takes nothing more. A capture can also be refused for good, such as when the hold has lapsed, so capture returns CAPTURED or REFUSED, and throws only when no answer comes back. pickUp relies on the promise about authorise:

rental/RentalService.javalines 116–151 of 316
    /** Places the hold and hands over the car. Returns the cents held. */    public long pickUp(String rentalId, String cardToken, Reading reading) {        Rental rental = rental(rentalId);        Objects.requireNonNull(cardToken, "cardToken");        Objects.requireNonNull(reading, "reading");        if (cardToken.isBlank()) {            throw new IllegalArgumentException("A pickup needs a card");        }        Trip trip = rental.trip();        Instant now = clock.instant();        if (now.isBefore(trip.pickupAt()) || !now.isBefore(trip.returnAt())) {            throw new NotAllowedException(rentalId + " can be picked up from " + trip.pickupAt()                    + " until " + trip.returnAt());        }        if (rental.status() != RentalStatus.BOOKED) {            throw new NotAllowedException(rentalId + " is " + rental.status() + " and cannot be picked up");        }        requireCarBack(rental);        long hold = Math.addExact(rental.priceCents(), trip.carClass().depositCents());        String key = rental.holdKey();        // No lock is held here, so a slow bank holds up only this counter.        if (!cards.authorise(key, cardToken, hold)) {            rental.renewHoldKey(key);            throw new PaymentDeclinedException(rentalId);        }        try {            rental.pickUp(reading, hold);        } catch (NotAllowedException refused) {            // A cancel got in first. After a double tap, the hold is in use and stays.            if (!rental.usesHold(key)) {                releaseQuietly(key);            }            throw refused;        }        return hold;    }
  1. Check the time and the status. A pickup is allowed from the booked pickup time until the booked return time.
  2. Check that the car is back (line 133). requireCarBack walks back through the car's earlier rentals, past any round trip nobody picked up. If a rental is still PICKED_UP, the car has not come back. If it is still BOOKED on a one-way trip, its customer never came and the car never moved. Either way the pickup is refused before the bank is asked.
  3. Work out the hold (line 134): the price plus the class's deposit, with Math.addExact. Asha's hold is $267.00 + $300.00 = $567.00.
  4. Ask the bank with the rental's key, and with no lock held.
  5. Hand over the car. Rental.pickUp moves the rental from BOOKED to PICKED_UP under its lock, and records the fuel, the odometer and the amount held.

Each rental gets a random UUID as its hold key when it is created. A key built from the rental id, such as R-1-hold, would repeat after a restart, because ids start at R-1 again. The bank would then answer a new customer with an old customer's hold.

If the card is declined, the car stays and the rental stays BOOKED. renewHoldKey gives the rental a fresh key, because the bank would answer the next card on the old key with the old decline. If the bank does not answer, the exception reaches the counter and nothing has changed. The key stays the same, so a retry gets back any hold the bank did place, instead of a second hold. Hotel Booking covers a bank that never answers. Here a cancel releases whatever the key holds. An unused hold also lapses after a period the card network sets, which for car rental can be about a month.

The last case is a refusal after the bank said yes. A cancel can land between the status check and Rental.pickUp. Then pickUp releases the hold it has just placed. A double tap at the counter reaches the same line by another path. Both taps pass the check, and both ask the bank with the same key, which holds once. One tap wins. The other must not release the hold, because the car is now using it, and usesHold tells the two cases apart.

Holding, then taking
pickUp() works out the hold, $267.00 plus the $300.00 deposit (1), and calls authorise with key K and no lock held. Approved: R-1 is PICKED_UP. Declined: the car stays, and R-1 gets a fresh key. No answer: the car stays, and a retry uses K again. At return (2), the bill of $424.75 is worked out before anything changes. Then capture asks for the smaller of the bill and the hold (3). If it is done, R-1 is CLOSED and the bank releases $142.25. Refused: nothing is taken, R-1 is CLOSED with the whole bill owed, and then the hold is released. With no answer, R-1 stays RETURNED until the job captures again with K. On the right, Gil's bill is above his hold, and a cancel releases K.pickUp() works out the hold, $267.00 plus the $300.00 deposit (1), and calls authorise with key K and no lock held. Approved: R-1 is PICKED_UP. Declined: the car stays, and R-1 gets a fresh key. No answer: the car stays, and a retry uses K again. At return (2), the bill of $424.75 is worked out before anything changes. Then capture asks for the smaller of the bill and the hold (3). If it is done, R-1 is CLOSED and the bank releases $142.25. Refused: nothing is taken, R-1 is CLOSED with the whole bill owed, and then the hold is released. With no answer, R-1 stays RETURNED until the job captures again with K. On the right, Gil's bill is above his hold, and a cancel releases K.
The bank holds the price and the deposit at pickup. At return it takes the bill and releases the rest. pickUp() works out the hold, $267.00 plus the $300.00 deposit (1), and calls authorise with key K and no lock held. Approved: R-1 is PICKED_UP. Declined: the car stays, and R-1 gets a fresh key. No answer: the car stays, and a retry uses K again. At return (2), the bill of $424.75 is worked out before anything changes. Then capture asks for the smaller of the bill and the hold (3). If it is done, R-1 is CLOSED and the bank releases $142.25. Refused: nothing is taken, R-1 is CLOSED with the whole bill owed, and then the hold is released. With no answer, R-1 stays RETURNED until the job captures again with K. On the right, Gil's bill is above his hold, and a cancel releases K.
Decision

When is the card used?

Charge the price when booking, and charge the extras at return

The booking is paid at once. But the extras are a second charge, made after the car has been driven for days, and it can be declined with nothing to fall back on.

Charge the price and the deposit at pickup, and refund the difference at return

The money then leaves the customer's account for the whole trip, and every return needs a refund, which can fail too.

Hold at pickup, and capture at returnOur pick

The bank keeps the money aside without taking it. Return takes exactly the bill, up to the hold, in one call, and the bank releases the rest. The cost is a gateway with three calls, and a capture that must be safe to repeat.

The final bill

billing/ChargeRule.javalines 3–8 of 8
/** One kind of charge added at return. Returns cents, zero when it does not apply. */public interface ChargeRule {    String name();     long chargeCents(ReturnFacts facts);}

The four rules read a ReturnFacts record: the trip, the readings at pickup and at return, the damage the inspector found, and the return time. Here is the late charge:

billing/LateReturnCharge.javalines 23–34 of 35
    @Override    public long chargeCents(ReturnFacts facts) {        Duration late = Duration.between(facts.trip().returnAt(), facts.returnedAt());        if (late.compareTo(grace) <= 0) {            return 0;        }        long startedHours = late.toHours();        if (late.compareTo(Duration.ofHours(startedHours)) > 0) {            startedHours++;        }        return Math.multiplyExact(startedHours, facts.trip().carClass().lateHourCents());    }

A return inside the grace costs nothing. Exactly 30 minutes late is still inside it. After that, every started hour from the booked return time is charged. FuelCharge charges each eighth of a tank below the pickup level, and extra fuel earns nothing back. MileageCharge allows 200 miles per day of the trip. DamageCharge charges the damage up to the $1,000 excess. Here is Asha's return, 2 hours 40 minutes late, with 3 eighths less fuel and 742 miles driven:

LineHow it is calculatedAmount
rental3 days at $89.00$267.00
late return3 started hours at $25.00$75.00
fuel3 eighths at $15.75$47.25
extra miles742 driven, 600 included: 142 at $0.25$35.50
total$424.75

billFor asks each rule in turn:

rental/RentalService.javalines 224–237 of 316
    private Bill billFor(Rental rental, ReturnFacts facts) {        List<BillLine> lines = new ArrayList<>();        lines.add(new BillLine("rental", rental.priceCents()));        for (ChargeRule rule : returnRules) {            long cents = rule.chargeCents(facts);            if (cents < 0) {                throw new IllegalStateException(rule.name() + " gave " + cents + " cents");            }            if (cents > 0) {                lines.add(new BillLine(rule.name(), cents));            }        }        return new Bill(lines);    }

A rule that gives a negative amount is a bug, so billFor throws IllegalStateException. Bill adds its lines with Math.addExact when it is created, so a total too large for a long throws instead of wrapping round. ReturnFacts refuses an odometer that went backwards, and damage below zero or above $100,000. In every one of these cases the rental is still PICKED_UP, and the bank has not been called.

Decision

How is the final bill built?

One method with an if for each charge

It is short today. But each new fee edits the class that holds the locks, and a charge can only be tested through a whole return.

A list of ChargeRules, each adding its own lineOur pick

A new fee is a new class in the list. Each rule is a small function of ReturnFacts, tested on its own, and the bill shows one line per rule that charged something. The cost is that rules cannot see each other, so a rule such as "members pay no fuel charge" needs membership in the facts.

Returning the car

rental/RentalService.javalines 153–168 of 316
    /** Works out the final bill, then captures it from the hold. */    public Bill returnCar(String rentalId, Reading reading, long damageCents) {        Rental rental = rental(rentalId);        Objects.requireNonNull(reading, "reading");        if (rental.status() != RentalStatus.PICKED_UP) {            throw new NotAllowedException(rentalId + " is " + rental.status() + " and cannot be returned");        }        Instant now = clock.instant();        ReturnFacts facts = new ReturnFacts(rental.trip(), rental.atPickup(), reading, damageCents, now);        long held = rental.heldCents();        Bill bill = billFor(rental, facts);        rental.markReturned(bill, Math.min(bill.totalCents(), held), now);        unsettled.add(rentalId);        settle(rental);        return bill;    }

returnCar works out the bill first (lines 160 to 163). Only then does Rental.markReturned record the bill and the amount to capture, under the rental's lock. A second return is refused there, before it reaches the bank. The rental goes into unsettled before the capture, and settle asks the bank:

rental/RentalService.javalines 239–256 of 316
    private boolean settle(Rental rental) {        CaptureResult result;        try {            result = cards.capture(rental.holdKey(), rental.captureCents());        } catch (RuntimeException noAnswer) {            // The money may have moved. The job captures again with the same key, which takes nothing twice.            return false;        }        if (result == null) {            return false;        }        boolean closed = result == CaptureResult.CAPTURED ? rental.close() : rental.closeUnpaid();        unsettled.remove(rental.id());        if (result == CaptureResult.REFUSED) {            releaseQuietly(rental.holdKey());        }        return closed;    }

If the capture gets no answer, the money may have moved. The rental stays RETURNED in unsettled, and a job calls retrySettlements, which captures again with the same key. The bank's promise makes this safe: a second capture with that key takes nothing more. Because the rental is queued before the call, even an Error from the gateway leaves it waiting for the job. Rental.close returns false if another call closed it first, so two jobs running at once count it once. The car is already back, so no customer waits while the bank works it out. A return still unsettled a day later is listed by settlementsForAPerson, as Hotel Booking hands a long-pending payment to a person.

If the bank refuses the capture, it will refuse every retry too, so settle does not queue it again. Rental.closeUnpaid closes the rental with nothing captured, owedCents shows the whole bill, and settle releases the key. A 30-day trip whose hold lapsed before the return ends up here.

Decision

The bill is more than the hold. What now?

Ask the bank for a bigger hold at return

It is a new call that can be declined at the counter, and then the company still has less money than it is owed.

Hold enough at pickup to cover anything

No hold is big enough for every kind of damage, and a large hold blocks the customer's money for the whole trip.

Capture the whole hold, and record the rest as owedOur pick

Return always finishes. In the demo, Gil's bill is $1,045.00 against a $245.00 hold, so $245.00 is captured and owedCents shows $800.00 for the claims team to collect. They find these with a report over closed rentals whose owedCents is above zero. Damage is assessed by a person anyway, so a person following up the rest fits how damage is handled.

Taking a car out of service

A car with a warning light goes to the workshop for a few hours. That is a block too, so the same checks run:

rental/CarSchedule.javalines 48–58 of 149
    /** The car stays where it is; refused if any block is in the way. */    synchronized void addMaintenance(String id, Instant from, Instant until) {        Branch here = placeAt(from);        Block block = new Block(id, Block.Kind.MAINTENANCE, from, until, here, here);        Optional<String> problem = problemWith(block);        if (problem.isPresent()) {            throw new NotAllowedException(car.id() + " cannot go out of service: " + problem.get());        }        byStart.put(block.start(), block);        startById.put(block.id(), block.start());    }

The block's branch is where the car will be when it starts, from placeAt (line 50), the lookup whereAt also uses, and a maintenance block can never move a car. It must start between now and 365 days ahead, like a booking, and last for up to 30 days. If a booking is in the way, the refusal names it. In the demo, SUV-1 cannot go in on Tuesday 8 December, because R-1 has it until Thursday 11:00. After maintenance the car is ready at once, with no inspection time.

The final design

RentalService is the core. It owns one CarSchedule per car and every Rental, and it reaches the charge rules and the bank only through interfaces. Each schedule and each rental guards its own state with its own lock, and no lock is held during a bank call. It reads the time only from the Clock it is given, so the demo moves from booking day to return day in one line.

The design we built
This figure shows the classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. CarSchedule carries 3, 5 and 6. RentalService carries 9, Rental carries 2, Branch carries 1, and Block carries 4. CardGateway carries 7 and ChargeRule carries 8, and a purple tag marks ChargeRule as a Strategy.This figure shows the classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. CarSchedule carries 3, 5 and 6. RentalService carries 9, Rental carries 2, Branch carries 1, and Block carries 4. CardGateway carries 7 and ChargeRule carries 8, and a purple tag marks ChargeRule as a Strategy.
Each decision lands on one class. One interface carries a pattern. This figure shows the classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. CarSchedule carries 3, 5 and 6. RentalService carries 9, Rental carries 2, Branch carries 1, and Block carries 4. CardGateway carries 7 and ChargeRule carries 8, and a purple tag marks ChargeRule as a Strategy.
S.No.The questionWhat we choseWhy
1Should a branch keep a list of its cars?No: a car's place comes from its own scheduleOne record of where each car is
2Does a booking hold a specific car or a class of car?A specific car, chosen when bookingWhether it is free and where it is come from one schedule
3How do we know where a car will be?Read it from the schedule: the block before ends where the car isThe schedule already holds every future move
4How does a returned car get time for inspection?A fixed two hours after every rental, in readyAt()The time exists before anyone needs it
5A cancelled one-way trip leaves a later booking without a car. What now?Keep the move as a staff transferEvery later booking keeps its car
6Where do the locks go?One lock per car's schedule, held only while checking and addingBookings wait only when they try the same car
7When is the card used?Hold at pickup, and capture at returnReturn takes exactly the bill in one call
8How is the final bill built?A list of ChargeRules, each adding its own lineA new fee is a new class
9The bill is more than the hold. What now?Capture the whole hold, and record the rest as owedReturn always finishes

Here is Asha's return from the demo, end to end:

  1. The LAX counter calls RentalService.returnCar for R-1. It checks that R-1 is PICKED_UP, and builds ReturnFacts with the time from clock.instant().
  2. billFor asks each ChargeRule for its amount: $75.00 late, $47.25 fuel and $35.50 miles. Bill adds them to the $267.00 price with Math.addExact, for $424.75. Nothing has changed yet.
  3. Rental.markReturned takes R-1's lock, checks the status again, and records the bill and the capture: the smaller of $424.75 and the $567.00 hold.
  4. returnCar adds R-1 to unsettled, and settle calls CardGateway.capture with R-1's hold key. This is the outside call, with no lock held. The bank takes $424.75 and releases $142.25.
  5. Rental.close moves R-1 to CLOSED under its lock, and settle removes it from unsettled.

Booking is the path where the schedule's lock matters: book calls CarSchedule.tryAdd on each car of the class, and each call checks and adds under that car's lock.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

rentalRentalService.java
package rental; import java.time.Clock;import java.time.Duration;import java.time.Instant;import java.util.ArrayList;import java.util.EnumMap;import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong; import billing.Bill;import billing.BillLine;import billing.ChargeRule;import billing.ReturnFacts;import exception.NoCarException;import exception.NotAllowedException;import exception.PaymentDeclinedException;import fleet.Branch;import fleet.Car;import fleet.CarClass;import fleet.Reading;import payment.CaptureResult;import payment.CardGateway;import trip.Trip; public class RentalService {    public static final Duration BOOKING_WINDOW = Duration.ofDays(365);    /** A return the bank has not answered for this long goes to a person. */    public static final Duration SETTLE_WITHIN = Duration.ofDays(1);     private final Map<String, CarSchedule> schedules = new LinkedHashMap<>();    private final Map<CarClass, List<CarSchedule>> schedulesByClass = new EnumMap<>(CarClass.class);    private final Set<Branch> branches;    private final List<ChargeRule> returnRules;    private final CardGateway cards;    private final Clock clock;    private final Map<String, Rental> rentals = new ConcurrentHashMap<>();    private final Set<String> unsettled = ConcurrentHashMap.newKeySet();    private final AtomicLong nextRentalId = new AtomicLong(1);    private final AtomicLong nextMaintenanceId = new AtomicLong(1);     public RentalService(List<Car> cars, Set<Branch> branches, List<ChargeRule> returnRules,            CardGateway cards, Clock clock) {        this.branches = Set.copyOf(Objects.requireNonNull(branches, "branches"));        this.returnRules = List.copyOf(Objects.requireNonNull(returnRules, "returnRules"));        this.cards = Objects.requireNonNull(cards, "cards");        this.clock = Objects.requireNonNull(clock, "clock");        Set<String> ruleNames = new HashSet<>();        for (ChargeRule rule : this.returnRules) {            if (!ruleNames.add(rule.name())) {                throw new IllegalArgumentException("Two charge rules are named " + rule.name());            }        }        for (Car car : List.copyOf(Objects.requireNonNull(cars, "cars"))) {            requireBranch(car.startsAt());            CarSchedule schedule = new CarSchedule(car);            if (schedules.putIfAbsent(car.id(), schedule) != null) {                throw new IllegalArgumentException("Two cars have the id " + car.id());            }            schedulesByClass.computeIfAbsent(car.carClass(), c -> new ArrayList<>()).add(schedule);        }        if (schedules.isEmpty()) {            throw new IllegalArgumentException("A rental company needs at least one car");        }    }     /** Books the first car of the class that fits the trip, or throws NoCarException. */    public Rental book(String customer, Trip trip) {        Objects.requireNonNull(customer, "customer");        Objects.requireNonNull(trip, "trip");        if (customer.isBlank()) {            throw new IllegalArgumentException("A booking needs a customer");        }        requireBranch(trip.pickupBranch());        requireBranch(trip.returnBranch());        requireInWindow(trip.pickupAt());        long price = trip.priceCents();        String id = "R-" + nextRentalId.getAndIncrement();        Block block = blockFor(id, trip);        for (CarSchedule schedule : schedulesByClass.getOrDefault(trip.carClass(), List.of())) {            if (schedule.tryAdd(block)) {                Rental rental = new Rental(id, customer, schedule.car(), trip, price);                rentals.put(id, rental);                return rental;            }        }        throw new NoCarException(trip);    }     public int carsFree(Trip trip) {        Block block = blockFor("query", Objects.requireNonNull(trip, "trip"));        int free = 0;        for (CarSchedule schedule : schedulesByClass.getOrDefault(trip.carClass(), List.of())) {            if (schedule.fits(block)) {                free++;            }        }        return free;    }     public void cancel(String rentalId) {        Rental rental = rental(rentalId);        Instant now = clock.instant();        rental.cancel();        schedules.get(rental.car().id()).cancel(rentalId, now);        // A pickup that got no answer from the bank may have left a hold under this key.        releaseQuietly(rental.holdKey());    }     /** Places the hold and hands over the car. Returns the cents held. */    public long pickUp(String rentalId, String cardToken, Reading reading) {        Rental rental = rental(rentalId);        Objects.requireNonNull(cardToken, "cardToken");        Objects.requireNonNull(reading, "reading");        if (cardToken.isBlank()) {            throw new IllegalArgumentException("A pickup needs a card");        }        Trip trip = rental.trip();        Instant now = clock.instant();        if (now.isBefore(trip.pickupAt()) || !now.isBefore(trip.returnAt())) {            throw new NotAllowedException(rentalId + " can be picked up from " + trip.pickupAt()                    + " until " + trip.returnAt());        }        if (rental.status() != RentalStatus.BOOKED) {            throw new NotAllowedException(rentalId + " is " + rental.status() + " and cannot be picked up");        }        requireCarBack(rental);        long hold = Math.addExact(rental.priceCents(), trip.carClass().depositCents());        String key = rental.holdKey();        // No lock is held here, so a slow bank holds up only this counter.        if (!cards.authorise(key, cardToken, hold)) {            rental.renewHoldKey(key);            throw new PaymentDeclinedException(rentalId);        }        try {            rental.pickUp(reading, hold);        } catch (NotAllowedException refused) {            // A cancel got in first. After a double tap, the hold is in use and stays.            if (!rental.usesHold(key)) {                releaseQuietly(key);            }            throw refused;        }        return hold;    }     /** Works out the final bill, then captures it from the hold. */    public Bill returnCar(String rentalId, Reading reading, long damageCents) {        Rental rental = rental(rentalId);        Objects.requireNonNull(reading, "reading");        if (rental.status() != RentalStatus.PICKED_UP) {            throw new NotAllowedException(rentalId + " is " + rental.status() + " and cannot be returned");        }        Instant now = clock.instant();        ReturnFacts facts = new ReturnFacts(rental.trip(), rental.atPickup(), reading, damageCents, now);        long held = rental.heldCents();        Bill bill = billFor(rental, facts);        rental.markReturned(bill, Math.min(bill.totalCents(), held), now);        unsettled.add(rentalId);        settle(rental);        return bill;    }     /** Run by a job: captures again for each return whose capture got no answer. Returns how many closed. */    public int retrySettlements() {        int closed = 0;        for (String rentalId : unsettled) {            if (settle(rentals.get(rentalId))) {                closed++;            }        }        return closed;    }     /** Returns the bank has not settled a day after the car came back. A person follows these up. */    public List<String> settlementsForAPerson() {        Instant cutoff = clock.instant().minus(SETTLE_WITHIN);        List<String> stuck = new ArrayList<>();        for (String rentalId : unsettled) {            if (rentals.get(rentalId).returnedAt().isBefore(cutoff)) {                stuck.add(rentalId);            }        }        return stuck;    }     public void takeOutOfService(String carId, Instant from, Instant until) {        CarSchedule schedule = schedule(carId);        Objects.requireNonNull(from, "from");        Objects.requireNonNull(until, "until");        if (!until.isAfter(from) || Duration.between(from, until).compareTo(Trip.LONGEST) > 0) {            throw new IllegalArgumentException("Out of service for up to " + Trip.LONGEST.toDays() + " days");        }        requireInWindow(from);        schedule.addMaintenance("M-" + nextMaintenanceId.getAndIncrement(), from, until);    }     public Branch whereIs(String carId, Instant time) {        return schedule(carId).whereAt(Objects.requireNonNull(time, "time"));    }     public List<Block> blocks(String carId) {        return schedule(carId).blocks();    }     public Rental rental(String rentalId) {        Rental rental = rentals.get(Objects.requireNonNull(rentalId, "rentalId"));        if (rental == null) {            throw new NotAllowedException("No rental " + rentalId);        }        return rental;    }     public int unsettledCount() {        return unsettled.size();    }     private Bill billFor(Rental rental, ReturnFacts facts) {        List<BillLine> lines = new ArrayList<>();        lines.add(new BillLine("rental", rental.priceCents()));        for (ChargeRule rule : returnRules) {            long cents = rule.chargeCents(facts);            if (cents < 0) {                throw new IllegalStateException(rule.name() + " gave " + cents + " cents");            }            if (cents > 0) {                lines.add(new BillLine(rule.name(), cents));            }        }        return new Bill(lines);    }     private boolean settle(Rental rental) {        CaptureResult result;        try {            result = cards.capture(rental.holdKey(), rental.captureCents());        } catch (RuntimeException noAnswer) {            // The money may have moved. The job captures again with the same key, which takes nothing twice.            return false;        }        if (result == null) {            return false;        }        boolean closed = result == CaptureResult.CAPTURED ? rental.close() : rental.closeUnpaid();        unsettled.remove(rental.id());        if (result == CaptureResult.REFUSED) {            releaseQuietly(rental.holdKey());        }        return closed;    }     /** Walks back through the car's earlier rentals, past any round trip nobody picked up. */    private void requireCarBack(Rental rental) {        for (String earlierId : schedules.get(rental.car().id()).rentalsBefore(rental.trip().pickupAt())) {            Rental previous = rentals.get(earlierId);            if (previous == null) {                return;            }            RentalStatus status = previous.status();            if (status == RentalStatus.CANCELLED) {                // A cancel still in progress: its block is about to become a transfer or go.                continue;            }            if (status == RentalStatus.BOOKED && !previous.trip().oneWay()) {                // A round trip nobody picked up left the car where it was.                continue;            }            if (status == RentalStatus.PICKED_UP || status == RentalStatus.BOOKED) {                // The car is still out, or a one-way no-show never moved it.                throw new NotAllowedException(rental.car().id() + " is not back from " + previous.id() + ", which is "                        + status);            }            return;        }    }     private void requireInWindow(Instant start) {        Instant now = clock.instant();        if (start.isBefore(now) || start.isAfter(now.plus(BOOKING_WINDOW))) {            throw new NotAllowedException("Start must be between now and " + BOOKING_WINDOW.toDays() + " days ahead");        }    }     private void releaseQuietly(String holdKey) {        try {            cards.release(holdKey);        } catch (RuntimeException bankDown) {            // The hold is unused. It lapses when the card network says, and a person can release it sooner.        }    }     private static Block blockFor(String id, Trip trip) {        return new Block(id, Block.Kind.RENTAL, trip.pickupAt(), trip.returnAt(), trip.pickupBranch(),                trip.returnBranch());    }     private CarSchedule schedule(String carId) {        CarSchedule schedule = schedules.get(Objects.requireNonNull(carId, "carId"));        if (schedule == null) {            throw new NotAllowedException("No car " + carId);        }        return schedule;    }     private void requireBranch(Branch branch) {        if (!branches.contains(Objects.requireNonNull(branch, "branch"))) {            throw new IllegalArgumentException("Unknown branch " + branch);        }    }}
Click a class name in the code to open its fileJava · 316 lines · 1400 in the project

demo/Main.java runs two branches, SFO and LAX, through the first ten days of December. Asha takes SUV-1 one way to LAX, and Ben books it there for the Friday after. Chen is refused, and Dev books and cancels. Ed's first card is declined, and the bank loses the answer to his capture. Gil returns a damaged car, and Asha returns late. A refused request still uses up a number, so Dev's booking is R-4:

$ java demo.Main
SUV-1 and SUV-2 start at SFO. ECO-1 starts at LAX.

-- Tue 1 Dec 08:00: bookings
R-1 Asha: SUV-1, SFO Mon 7 Dec 09:00 to LAX Thu 10 Dec 09:00, $267.00
SUVs free for a trip from LAX on Fri 11 Dec 10:00: 1
R-2 Ben: SUV-1, LAX Fri 11 Dec 10:00 to SFO Mon 14 Dec 10:00, $267.00
Chen: refused, no SUV for LAX Thu 10 Dec 10:00 to LAX Thu 10 Dec 18:00
R-4 Dev: SUV-2, SFO Sun 6 Dec 09:00 to LAX Sun 6 Dec 21:00, $89.00
R-5 Ed: SUV-2, LAX Tue 8 Dec 10:00 to LAX Wed 9 Dec 10:00, $89.00
R-6 Gil: ECO-1, LAX Tue 8 Dec 12:00 to LAX Wed 9 Dec 12:00, $45.00
Refused: SUV-1 cannot go out of service: busy with R-1 until 2026-12-10T11:00:00Z

-- Wed 2 Dec 09:00: Dev cancels R-4
SUV-2: R-4 TRANSFER SFO to LAX, Sun 6 Dec 09:00 to Sun 6 Dec 21:00
SUV-2: R-5 RENTAL LAX to LAX, Tue 8 Dec 10:00 to Wed 9 Dec 10:00

-- Mon 7 Dec 09:00: Asha picks up
R-1 picked up. Held on card-asha: $567.00

-- Tue 8 Dec 10:00: Ed picks up
R-5: The card was declined for R-5; the car stays at the branch
R-5 picked up. Held on card-ed: $389.00

-- Tue 8 Dec 12:00: Gil picks up
R-6 picked up. Held on card-gil: $245.00

-- Wed 9 Dec 10:00: Ed returns, and the bank's answer is lost
R-5 returned. Bill: rental $89.00. Total $89.00
  R-5 RETURNED. Capture $89.00, release $300.00, owed $0.00
Settlement job closed 1 rental
  R-5 CLOSED. Capture $89.00, release $300.00, owed $0.00

-- Wed 9 Dec 12:00: Gil returns with $1,450.00 of damage
R-6 returned. Bill: rental $45.00, damage $1,000.00. Total $1,045.00
  R-6 CLOSED. Capture $245.00, release $0.00, owed $800.00

-- Wed 9 Dec 14:00: SUV-2 goes in for a check
SUV-2 out of service at LAX until Wed 9 Dec 18:00

-- Thu 10 Dec 11:40: Asha returns late
R-1 returned. Bill: rental $267.00, late return $75.00, fuel $47.25, extra miles $35.50. Total $424.75
  R-1 CLOSED. Capture $424.75, release $142.25, owed $0.00

The bank captured $758.75 in all

Notice three things in the output. Before Ben books, one SUV is free for his trip from LAX, although both SUVs start at SFO: R-1 brings SUV-1 there. After Dev cancels, SUV-2's schedule still shows R-4 as a TRANSFER to LAX, so Ed's R-5 keeps its car. And the bank captured $758.75 in all, which is Ed's $89.00, Gil's $245.00 and Asha's $424.75, so the retry with Ed's key took nothing more.

Follow-up questions

After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Pick the car that leaves the fewest gaps."A chooser interface that orders the cars book tries, such as the car whose last block ends nearest the pickup.CarSchedule and its checks.
"Let customers return to a different branch."returnCar takes the branch, and the car's block is replaced with one that ends there. A later block that starts elsewhere needs a transfer or another car. A drop fee is one more ChargeRule.The hold and the other rules.
"A late return makes the next customer wait."A job at each block's readyAt checks that the car is back. If not, it moves the next booking to another car with tryAdd, and frees the old block.Billing and the hold.
"Free the rest of the trip when a car comes back early."returnCar shortens the block to the return time, under the schedule's lock. A refund for unused days needs a negative line, which BillLine and billFor refuse today.The chain checks.
"A car breaks down with bookings ahead."A method that moves each later booking to another car through tryAdd, and cancels with a message any booking no car fits.Rental, billing and the hold.
"Add insurance that lowers the excess."The rental records the option. DamageCharge reads the excess from ReturnFacts instead of its constructor, and the price adds a daily fee.Schedules and locks.
"Charge more at weekends."Trip.priceCents moves behind a rate rule that prices day by day, as on the Hotel Booking page.Schedules and the hold.
"Keep the schedules small."A job drops blocks that ended long ago, keeping the latest one, so whereAt still knows where the car is.Every check.
"A customer never comes to pick up."A job cancels the BOOKED rental during its booked hours, so a driver can make the transfer. The cancel keeps the transfer if a later booking needs the car, so requireCarBack lets the next pickup through.The chain checks and billing.
"The company has thousands of cars."book first skips cars that will be at another branch, with a quick whereAt read, and tries tryAdd only on the rest. An index of cars by branch and day can come later.tryAdd, which still checks under the lock.
"Run on many servers."Each car's blocks move to a database, with a row lock per car, so two servers cannot add to one car at once.The rules and the gateway.

In most rows the change lands in a new rule, a new job or a new method beside the core, and CarSchedule.tryAdd stays as it is. Two rows are bigger. A return to another branch and a late return both change a block after later bookings were made, so they need a way to move bookings between cars.

What the interviewer looks for

Mid-level

A mid-level candidate shows clear classes for cars, rentals and branches, prices in integer cents, and a check that a car is free before booking it. They say that two customers could take one car at once and that some locking is needed, even if the lock covers more than it has to.

Senior

A senior candidate shows everything above and gives the reasons. They notice that a one-way trip moves the car, and check both the time and the place against the car's two neighbours under one lock per car. They hold the card at pickup and capture at return, with the bank call outside the lock. They work out the bill before changing any state.

Staff+

A staff candidate leads the conversation through the trade-offs without being asked. They explain why a cancelled one-way trip must still move the car, and why a key from the rental id breaks after a restart. They name what the design leaves open, such as a late return that delays the next customer.

Common mistakes

  • A count of cars per branch. A one-way trip makes the count wrong for every day after it.
  • Checking only the time. A booking can be free in time and still start where the car is not, or strand the next booking.
  • Removing a cancelled one-way trip. Later bookings of that car lose their car.
  • Charging the card when booking. The extras then need a second charge after the car has gone.
  • A hold key built from the rental id. After a restart the ids repeat, and the bank answers with another customer's hold.
  • Releasing the hold on every failed pickup. A double tap then frees the hold that the car is using.
  • Changing state before the bill is known. A rule that throws leaves a rental returned with no bill.

Summary

  • Ask first whether cars can be returned to another branch. One-way trips mean a car's place changes, and counts per branch stop working.
  • A booking holds one specific car. Its schedule says both when the car is free and where it will be.
  • A new block is checked against its two neighbours for time and place, under one lock per car.
  • A cancelled one-way trip with later bookings stays as a staff transfer.
  • Hold the price and the deposit at pickup, and capture the bill at return. A random key makes a call with no answer safe to repeat. A decline gets a fresh key, and a refused capture is owed, not retried.
  • Work out the whole bill from a list of rules before changing anything. Capture up to the hold, and record the rest as owed.
  • Keep the bank call outside every lock.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.