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.

Intermediate 4 min readLesson 9 of 14

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

ClientLoad balancerTLS, routingMiddlewareauth, logging, CORSHandlervalidate, call serviceService + repobusiness logicDatabase
  1. The client sends an HTTP request (HTTP).
  2. A reverse proxy / load balancer terminates TLS and forwards it to an app instance.
  3. Middleware runs cross-cutting concerns.
  4. The router matches method + path to a handler.
  5. The handler validates input, calls business logic, which reads/writes data.
  6. 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);
    }
}

Middleware

Middleware wraps every request (or a group of routes) — a chain of responsibility (Chain of responsibility):

JavaScript
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 routes

Typical middleware: request IDs, logging, CORS, compression, body parsing, authentication, rate limiting (Rate limiting), error handling.

Layered architecture

Keep HTTP concerns out of business logic:

LayerResponsibilityKnows about
Controller / handlerParse and validate the request, map to and from DTOs, choose status codesHTTP
ServiceBusiness rules, orchestration, transactionsDomain
Repository / data accessQueries and persistenceDatabase
Domain modelsEntities and invariantsNothing 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

ApproachExamplesTrade-off
Raw SQL / query builderpg, JDBC, SQLAlchemy Core, Knex, jOOQFull control; more code
ORMHibernate/JPA, SQLAlchemy ORM, Django ORM, Prisma, Drizzle, TypeORMProductivity; risk of hidden inefficient queries

The classic ORM pitfall is the N+1 query problem:

Python
# ✗ 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 (/healthz liveness, /readyz readiness) for load balancers and orchestrators (Kubernetes).
  • Graceful shutdown: on SIGTERM, stop accepting connections, finish in-flight requests, close pools.

Concurrency models

ModelExamplesNotes
Thread per requestSpring MVC (classic), Django (WSGI)Simple; threads are memory-heavy — virtual threads fix this (Virtual threads)
Event loop, async I/ONode.js, FastAPI/asyncio, Spring WebFluxMany connections per thread; never block the loop (Node internals)
Goroutines / green threadsGo, Erlang/ElixirCheap 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.

Key takeaways
  • 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.