Backend Fundamentals
What a web backend does — the request lifecycle, routing, middleware, controllers and layered architecture, validation, persistence with ORMs, configuration, background jobs, logging and errors — with examples in Express, FastAPI and Spring Boot.
A backend receives requests from clients (browsers, mobile apps, other services), runs business logic, reads and writes data, and returns responses. Frameworks differ in syntax, but the building blocks are the same everywhere.
The request lifecycle
- The client sends an HTTP request (HTTP).
- A reverse proxy / load balancer terminates TLS and forwards it to an app instance.
- Middleware runs cross-cutting concerns.
- The router matches method + path to a handler.
- The handler validates input, calls business logic, which reads/writes data.
- A response (status, headers, body — usually JSON) goes back, passing through middleware again.
Routing and handlers
// Spring Boot
@RestController
@RequestMapping("/api/users")
class UserController {
private final UserService users;
UserController(UserService users) { this.users = users; } // constructor injection
@GetMapping("/{id}")
ResponseEntity<UserDto> get(@PathVariable long id) {
return users.find(id).map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
ResponseEntity<UserDto> create(@Valid @RequestBody CreateUser req) {
UserDto created = users.create(req);
return ResponseEntity.created(URI.create("/api/users/" + created.id())).body(created);
}
}# FastAPI
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, EmailStr
app = FastAPI()
class CreateUser(BaseModel): # validation from type hints
email: EmailStr
name: str
@app.get("/api/users/{user_id}")
async def get_user(user_id: int, svc: UserService = Depends(get_user_service)):
user = await svc.find(user_id)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
@app.post("/api/users", status_code=201)
async def create_user(body: CreateUser, svc: UserService = Depends(get_user_service)):
return await svc.create(body)// Express + zod
import express from "express";
import { z } from "zod";
const app = express();
app.use(express.json());
const CreateUser = z.object({ email: z.string().email(), name: z.string().min(1) });
app.get("/api/users/:id", async (req, res) => {
const user = await userService.find(Number(req.params.id));
if (!user) return res.status(404).json({ error: "User not found" });
res.json(user);
});
app.post("/api/users", async (req, res) => {
const parsed = CreateUser.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ errors: parsed.error.issues });
const user = await userService.create(parsed.data);
res.status(201).location(`/api/users/${user.id}`).json(user);
});
app.listen(3000);Middleware
Middleware wraps every request (or a group of routes) — a chain of responsibility (Chain of responsibility):
app.use((req, res, next) => { // logging + timing
const start = performance.now();
res.on("finish", () => log.info({ method: req.method, path: req.path,
status: res.statusCode, ms: performance.now() - start }));
next(); // pass control to the next middleware
});
app.use(cors({ origin: "https://app.example.com" }));
app.use("/api", requireAuth); // only for /api routesTypical middleware: request IDs, logging, CORS, compression, body parsing, authentication, rate limiting (Rate limiting), error handling.
Layered architecture
Keep HTTP concerns out of business logic:
| Layer | Responsibility | Knows about |
|---|---|---|
| Controller / handler | Parse and validate the request, map to and from DTOs, choose status codes | HTTP |
| Service | Business rules, orchestration, transactions | Domain |
| Repository / data access | Queries and persistence | Database |
| Domain models | Entities and invariants | Nothing external |
Benefits: services are unit-testable without HTTP, the database can change behind the repository, and the same logic can serve REST, GraphQL, a CLI or a queue consumer. Dependencies are wired with dependency injection (Dependency injection).
Validation
Never trust input. Validate type, format, range and size at the boundary, and return 400 (malformed) or 422 (semantically invalid) with useful messages. Schema libraries make validation declarative: zod (TS), Pydantic (Python), Bean Validation (@NotNull, @Email) in Java.
Persistence
| Approach | Examples | Trade-off |
|---|---|---|
| Raw SQL / query builder | pg, JDBC, SQLAlchemy Core, Knex, jOOQ | Full control; more code |
| ORM | Hibernate/JPA, SQLAlchemy ORM, Django ORM, Prisma, Drizzle, TypeORM | Productivity; risk of hidden inefficient queries |
The classic ORM pitfall is the N+1 query problem:
# ✗ 1 query for posts + N queries for authors
for post in session.query(Post).all():
print(post.author.name)
# ✓ eager-load in one or two queries
for post in session.query(Post).options(selectinload(Post.author)):
print(post.author.name)Other essentials: a connection pool (opening DB connections is expensive), migrations in version control (Flyway, Alembic, Prisma Migrate), transactions around multi-step changes (Transactions), and indexes for your query patterns (Indexing).
Configuration and secrets
Follow the twelve-factor approach: configuration comes from the environment (env vars, a secrets manager), never hard-coded or committed. The same build artefact runs in dev, staging and production with different config.
Background work
Don't make users wait for slow or unreliable work. Return quickly and enqueue a job:
- Sending emails, generating PDFs, resizing images, calling slow third-party APIs, webhooks.
- Tools: BullMQ (Node), Celery / RQ / Dramatiq (Python), Spring
@Async, Sidekiq (Ruby), or a message broker (Message queues). - Jobs should be idempotent and retried with backoff.
- Scheduled tasks (cron jobs) for reports and cleanups.
Errors and observability
- A central error handler maps exceptions to status codes and a consistent error body; never leak stack traces to clients.
- Structured logs (JSON) with a request ID that travels through services; metrics (latency, error rate, throughput) and traces (Observability).
- Health checks (
/healthzliveness,/readyzreadiness) for load balancers and orchestrators (Kubernetes). - Graceful shutdown: on SIGTERM, stop accepting connections, finish in-flight requests, close pools.
Concurrency models
| Model | Examples | Notes |
|---|---|---|
| Thread per request | Spring MVC (classic), Django (WSGI) | Simple; threads are memory-heavy — virtual threads fix this (Virtual threads) |
| Event loop, async I/O | Node.js, FastAPI/asyncio, Spring WebFlux | Many connections per thread; never block the loop (Node internals) |
| Goroutines / green threads | Go, Erlang/Elixir | Cheap concurrency with blocking-style code |
Keep app servers stateless (sessions in Redis or tokens, files in object storage) so you can run many instances behind a load balancer and scale horizontally.
- Request → load balancer → middleware → router → handler → service → repository → database, and back.
- Middleware handles cross-cutting concerns; handlers stay thin.
- Layer the code: controllers (HTTP), services (business logic), repositories (data).
- Validate all input at the boundary with schemas; return clear 4xx errors.
- Use connection pools, migrations, and eager loading to avoid N+1 queries.
- Config from the environment; slow work in idempotent background jobs; structured logs, health checks and graceful shutdown; stateless instances.