Key idea
Most web apps grow into four parts: a web frontend people visit, an API that holds the rules, a database that keeps the data, and a worker that does slow jobs in the background. Only the API and the worker talk to the database.
browser
│ HTTPS
▼
┌───────┐ HTTPS ┌───────┐ TLS ┌──────────┐ TLS ┌────────┐
│ web │ ───────▶ │ API │ ───────▶ │ database │ ◀─────── │ worker │
└───────┘ └───────┘ └──────────┘ └────────┘
web service web service hosted elsewhere background worker
The four parts
Web. What the visitor's browser loads: a server-rendered app, or the built files of a single-page app. It shows things and collects input, then asks the API for everything else.
In a small server-rendered app, the web part and the API are often one service that reads the database itself, as in lesson 2.1.2. This lesson shows them apart, the shape most apps grow into.
API. The rules of the product: who may do what, what an order looks like, which status code to return. It's the only part the web talks to, and the one that reads and writes the database for requests.
Database. The records: users, orders, jobs. It keeps them across every deploy, so nothing else needs to keep data on its own disk.
Worker. Work that shouldn't hold up a request: sending the confirmation email, making the PDF, calling a slow partner API. It has no address, and nothing calls it.
How a job reaches the worker
The API and the worker never call each other. They meet in the database:
- A customer places an order. The API saves it and adds a row to a
jobstable: "send confirmation for order 42". - The API answers straight away, with 201 Created.
- The worker checks the
jobstable every few seconds, finds the new row, sends the email and marks the job done.
If the worker is down for a minute, jobs wait in the table and nothing is lost. As the app grows, the table can be swapped for a dedicated queue service.
On ComputeSphere
- Web: a web service. A single-page app's built files can be a static site instead.
- API: a web service, with its own URL.
- Worker: a background worker, with no URL.
- Database: hosted by a database provider, because ComputeSphere doesn't run databases. The API and the worker get its connection string as a secret.
All three services sit in one environment, so staging gets its own copies of all three, pointed at a staging database.
Keeping the web-to-API call off the internet
By default the web service calls the API at the API's public URL. An environment can have Private network turned on, so its services reach each other by a private address instead. It's chosen when the environment is created; lesson 5.5.3 shows how.
Check yourself