Thirty lines about returning a scooter
The handler for POST /rentals/{id}/return in a scooter-rental backend is 340 lines long, and about thirty of them are about returning a scooter.
The rest parses the JSON body, checks the rider's token, opens a database connection, selects the rental and the scooter with hand-written SQL, works out the fare (an unlock fee, a per-minute rate, a €25 daily cap, a €10 fee when the scooter is left outside a parking zone), updates three tables, commits, sends the receipt email and builds the HTTP response. Nobody minded until a second way to end a rental arrived.
Then the company put docks at train stations. A dock reports a return as a message on a queue, and the queue consumer needs everything the handler does except the HTTP: the same rental, the same fare, the same commit. It cannot call the handler, which expects a request and writes a response. The obvious move was to copy three hundred lines and change both copies with every fare change from then on. The real trouble was older than the docks: the use case, returning a scooter, had no place of its own.
One door per use case
So it gets one. ReturnVehicle becomes an object whose only job is to run that use case, and both the HTTP handler and the dock consumer call it. DDD calls such an object an Application Service, the entry point for one use case of the domain. It takes a plain input object, a command such as ReturnVehicle { rentalId: 88412, location, returnedAt }, and gives back a plain result, the fare and duration of the ended rental, not a status code or a response body. Inside, it does the same few things every time:
- It loads rental 88412 through the rental's Repository.
- It calls
rental.end(location, returnedAt), and the rental works out the fare and enforces its own rules. - It saves the rental through the repository.
- It commits the transaction.
- It publishes the events the rental recorded, such as
RentalEnded. - It returns the result to whoever called it.
The HTTP handler shrinks to parsing the body, checking the token, calling ReturnVehicle and turning the result into a response. The dock consumer does the same with its message. A fare rule changed once is changed for both, because neither of them contains it.
Both entry points send the same command. The application service loads and saves through the repository, lets the rental decide, and publishes what the rental recorded once the commit has succeeded.
Why the fare rule goes one level lower
A month later operations wants a second use case: ending the rentals of scooters found abandoned, which a field worker triggers from an app in the van. That is another application service, ForceEndRental, with its own input and its own caller. Had the fare calculation simply moved from the HTTP handler into ReturnVehicle, it would now be copied again, one level down. So the rules go below the application services, into the rental itself. rental.end() applies the cap and the zone fee and refuses to end a rental that has already ended, and every use case that ends a rental goes through the rental's own methods and gets the same rules.
The application service is defined as much by what it leaves out. The cap, the zone fee and whether a rental can end at all sit in the Aggregate. Status codes, headers and JSON stay in the handler, so the dock consumer, a test and an admin script can call the service without faking a request. SQL stays behind the repository: the service asks for rental 88412 and gets a rental. When a rule needs more than one aggregate and belongs to neither, such as a fare that combines the rental's minutes with the rider's monthly pass, the application service in this design loads both the rental and the pass and hands them to a Domain Service, which makes the decision; neither the domain service nor the rental fetches or saves anything.
Where the transaction starts and ends
The application service is also the transaction boundary for its use case, because it is the one object that knows where the use case ends. It opens the transaction before loading the rental and commits once, after saving it, in its own code or through a wrapper around it; if the rental refuses to end or the save fails, nothing is committed and the caller gets the failure. The repository saves but never commits on its own; if it did, one use case would again be split across several transactions, and a failure halfway would leave the first half written. Unit of Work handles how the changes are collected and written in that one commit.
The scooter has to become available again, and it is a different aggregate from the rental. Here the service does not update both in one transaction: it publishes RentalEnded after the commit, and the fleet module marks scooter 3307 available when it receives the event. The guideline of changing one aggregate per transaction, and when to break it, comes from Aggregate, and Domain Event walks through why events go out after the commit and what that timing can still lose.
A rider's app that retries a timed-out return runs the use case a second time; an Idempotency Key lets the service recognise the repeat and answer with the first result.
How the 340 lines come back
The bulk returns one convenience at a time. Usually it starts with a condition on the domain's data: if (fare > dailyCap) fare = dailyCap, written in ReturnVehicle, works until ForceEndRental needs the same cap. An if that decides or repeats a rental rule, as this cap does, moves down into the aggregate or a domain service; a condition that only coordinates the use case stays in the application service.
Next comes reaching into another aggregate. Decrementing dock.freeSlots from ReturnVehicle enforces the dock's rule from outside the dock, where any other use case that touches a dock can skip it; routing the change through the dock's own behaviour, such as dock.occupySlot(), or through a domain service, keeps the rule where every caller meets it.
Then the service starts calling other application services, SendReceipt and UpdateRiderStats, until nobody can say where the use case or its transaction ends. Follow-ups to a return can react to RentalEnded instead, and a rule such as "whenever a rental ends outside a zone, schedule a pickup" is a Policy (reactive rule). Last, a signature that takes the HTTP request or returns a database row ties the service to the transport or to the storage again, and every other caller has to work around it, which is how the 340 lines began.
The use case, said aloud
The DDD Tactical Building Blocks Challenge places six building blocks around one use case, and its first requirement is "Model an Application Service orchestrating the use case without business rules". Choose a use case with a rule worth protecting, such as ending a rental under a daily cap, so your Grid has a decision that must live somewhere other than the application service. When the design is right, the application service's part of it reads like the use case said aloud: load the rental, end it, save, commit. The cap, the zone fee and whether the rental may end at all sit on the Aggregate, or on a Domain Service when they need more than one aggregate and belong to neither, and nothing near the application service says unless or only if about them; its own conditions are coordination, such as a rental that does not exist.