# Backend Developer roadmap

> Build, secure, scale and operate server-side applications, APIs and data systems from first HTTP request to production.

Canonical: https://www.internhack.in/roadmaps/tracks/backend
Last updated: 2026-11-28

20 sections, 92 topics, about 445 hours.

A complete path to becoming a backend engineer. You start with how the internet and HTTP work, pick a server language, and learn the terminal and Git. Then you go deep on relational databases, API design, authentication and web security, testing and CI/CD, and caching. Later sections cover everyday product features (file uploads, email, payments), NoSQL and search, scaling databases, containers and web servers, architecture and design patterns, message brokers and real-time communication, observability, and building for scale and resilience. It ends with design reviews and a production-grade capstone project.

## Outcomes

- Explain what happens from a DNS lookup to a database query and back for any request your service handles
- Design, document and version REST, GraphQL or gRPC APIs with consistent errors, pagination and rate limits
- Model data in relational and NoSQL stores, write efficient queries, and use transactions, indexes and migrations safely
- Secure services with proper authentication, authorization, password hashing, TLS and OWASP defenses
- Test, containerize and continuously deploy a backend with CI/CD and zero-downtime releases
- Scale systems with caching, queues, replicas and horizontal scaling while staying resilient to failures
- Operate services in production using structured logs, metrics, tracing and profiling
- Ship a production-grade capstone backend and review designs like a senior engineer

## Prerequisites

- Comfort with at least one programming language (variables, functions, loops, data structures)
- Basic familiarity with using a computer's file system and installing software
- Helpful but not required: a little HTML and JavaScript to build simple clients

## How Requests Reach Your Server

The networking ground floor: what happens between a user typing a URL and your code receiving a request.

### How the Internet Moves Data

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/internet-basics

Understand packets, IP addresses, ports, TCP and UDP well enough to reason about where a request can fail.

The internet is a network of networks that forwards small chunks of data called **packets** from one machine to another. Every device has an **IP address** (IPv4 like `203.0.113.7` or IPv6 like `2001:db8::1`), and every program listening for traffic binds to a **port** (443 for HTTPS, 5432 for PostgreSQL). An address plus a port identifies one conversation endpoint.

Two transport protocols matter most to a backend developer:

- **TCP** gives you a reliable, ordered byte stream. It performs a handshake, retransmits lost packets and slows down when the network is congested. HTTP/1.1, HTTP/2, database drivers and most APIs ride on TCP.
- **UDP** just fires datagrams with no delivery guarantee. It is used where speed beats reliability (DNS lookups, video calls) and underneath **QUIC**, which powers HTTP/3.

#### Why this matters on the server side
When something is "slow" or "down", the cause is often below your code: a firewall blocking a port, a connection timing out during the TCP handshake, or latency between regions. Knowing the layers lets you ask the right question: is the name resolving, is the port reachable, is the TLS handshake finishing, or is my handler slow?

#### Pitfalls
- Confusing **latency** (time for one round trip) with **bandwidth** (how much data per second). Chatty APIs suffer from latency even on fast links.
- Binding a server to `127.0.0.1` and wondering why other machines cannot reach it; `0.0.0.0` listens on all interfaces.

You are ready to move on when you can sketch the path of a request from a laptop to a server and name what happens at each hop.

Key concepts: IP addresses (IPv4 and IPv6), Ports and sockets, TCP handshake and reliability, UDP and QUIC, Latency vs bandwidth, Routers, NAT and firewalls, OSI and TCP/IP layer models.

Mini project: Write a tiny TCP echo server and client using your language's socket library, then use a tool like netcat or telnet to talk to it from another terminal.

Self-check: Why might an API that makes 40 small sequential calls feel slow even on a gigabit connection?

Resources:
- [Cloudflare Learning Center](https://www.cloudflare.com/learning/) (Cloudflare)
- [MDN: How the web works](https://developer.mozilla.org/en-US/docs/Learn_web_development/Getting_started/Web_standards/How_the_web_works) (MDN)

### HTTP in Depth

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/http-protocol

Learn the request/response model, methods, status codes, headers and the differences between HTTP versions.

HTTP is the language your backend speaks with browsers, mobile apps and other services. A **request** has a method, a path, headers and an optional body. A **response** has a status code, headers and an optional body. Everything else (REST, GraphQL over HTTP, webhooks) is built on these pieces.

#### The parts you use every day
- **Methods**: `GET` reads, `POST` creates or triggers, `PUT` replaces, `PATCH` partially updates, `DELETE` removes. `GET`, `PUT` and `DELETE` are meant to be **idempotent**: repeating them has the same effect as doing them once.
- **Status codes**: 2xx success, 3xx redirection, 4xx the client did something wrong, 5xx the server failed. Learn the common ones: 200, 201, 204, 301, 304, 400, 401, 403, 404, 409, 422, 429, 500, 502, 503.
- **Headers**: metadata such as `Content-Type`, `Authorization`, `Cache-Control`, `Cookie` and `Accept`.

#### Versions
HTTP/1.1 sends one request at a time per connection. HTTP/2 multiplexes many requests over a single TCP connection with compressed headers. HTTP/3 runs over QUIC (UDP) to avoid head-of-line blocking. As a backend developer you mostly get HTTP/2 and HTTP/3 for free from your proxy or CDN, but you should know they exist.

#### Pitfalls
- Returning `200 OK` with an error message in the body. Clients, proxies and monitoring rely on status codes.
- Using `GET` for actions that change data. Crawlers and prefetchers will trigger them.

You are ready to move on when you can read a raw request and response (for example with `curl -v`) and explain every line.

Key concepts: Request and response anatomy, HTTP methods and idempotency, Status code families, Common headers, Content negotiation, HTTP/2 and HTTP/3, curl and browser devtools.

Mini project: Without any framework, build a server using only your language's built-in HTTP module that serves a JSON endpoint, a 404 for unknown paths and a 405 for wrong methods. Inspect it with curl -v.

Self-check: What is the practical difference between a 401 and a 403 response?

Resources:
- [MDN HTTP documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP) (MDN)
- [RFC 9110: HTTP Semantics](https://www.rfc-editor.org/rfc/rfc9110) (IETF)

### DNS and Domain Names

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/dns

Learn how names resolve to addresses, the common record types and how TTLs affect deployments.

The **Domain Name System** turns human names like `api.example.com` into IP addresses. When a client needs an address it asks a **recursive resolver** (from the ISP or a public one like 1.1.1.1), which walks the hierarchy: root servers, then the `.com` TLD servers, then the **authoritative** name servers for `example.com`. Answers are cached along the way for as long as the record's **TTL** allows.

#### Records a backend developer touches
- **A / AAAA**: name to IPv4 / IPv6 address.
- **CNAME**: alias one name to another (you cannot put a CNAME at the zone apex on most providers).
- **MX**: mail servers for the domain.
- **TXT**: free text, used for domain verification, SPF and DKIM email authentication.
- **NS**: which servers are authoritative for the zone.

#### Why it matters
DNS is part of every deployment. Pointing a domain at a new load balancer, verifying a domain for an email provider or switching hosting all mean editing records. Because of caching, a change is not instant: if the old record had a TTL of one day, some clients may keep the old address for a day. A common practice is to lower the TTL well before a planned migration.

#### Pitfalls
- Forgetting that failures can be cached too (negative caching).
- Debugging "the site is down" without checking whether the name resolves. Use `dig` or `nslookup` first.

You are ready to move on when you can register a domain (or use a free subdomain), point it at a server and explain what `dig` shows you.

Key concepts: Resolvers and authoritative servers, A, AAAA and CNAME records, MX and TXT records, TTL and caching, dig and nslookup, DNSSEC.

Mini project: Point a domain or free subdomain at a small server, then use dig to trace the lookup from the root servers down with dig +trace.

Self-check: You changed an A record 10 minutes ago but some users still hit the old server. Why, and how could you have prevented it?

Resources:
- [What is DNS?](https://www.cloudflare.com/learning/dns/what-is-dns/) (Cloudflare)
- [MDN glossary: DNS](https://developer.mozilla.org/en-US/docs/Glossary/DNS) (MDN)

### Where Backends Run: Hosting Options

core · beginner · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/hosting-basics

Compare shared hosting, VPS, PaaS, containers and serverless so you can put a real app online.

Your code has to run on some computer that is reachable from the internet. The options form a spectrum from "you manage everything" to "you manage almost nothing":

- **Virtual private server (VPS)**: a rented Linux machine (for example from DigitalOcean, Hetzner, Linode or an EC2 instance). Full control, but you patch the OS, configure the firewall and keep the process running.
- **Platform as a Service (PaaS)**: you push code or a container and the platform builds, runs, scales and gives you HTTPS (Render, Railway, Fly.io, Heroku, Google Cloud Run). Great for learning and small teams.
- **Managed containers / Kubernetes**: you ship images and the platform schedules them. More power, more concepts.
- **Serverless functions**: you upload handlers that run per request (AWS Lambda, Cloudflare Workers). No servers to manage, but cold starts and execution limits apply.

#### The big three cloud providers
AWS, Google Cloud and Azure offer all of the above plus managed databases, queues and storage. You do not need to learn them all; learn the concepts (compute, storage, networking, IAM) once and they transfer.

#### What to watch for
- **Cost surprises**: egress bandwidth, idle databases and forgotten resources add up. Set budget alerts.
- **State**: a process on a PaaS can be restarted at any time, so never store uploads or sessions on local disk.

You are ready to move on when you have deployed at least one app to a PaaS and one to a plain VPS, and can explain the trade-off you felt between them.

Key concepts: VPS and bare virtual machines, PaaS platforms, Serverless functions, AWS, GCP and Azure basics, Environment variables and config, Cost and budget alerts.

Mini project: Deploy the same hello-world API twice: once to a free PaaS tier and once to a small VPS behind a firewall with only ports 22, 80 and 443 open.

Self-check: Why is saving user uploads to the local filesystem risky on most PaaS platforms?

Resources:
- [What is the cloud?](https://www.cloudflare.com/learning/cloud/what-is-the-cloud/) (Cloudflare)
- [Render documentation](https://render.com/docs) (Render)
- [Heroku Dev Center](https://devcenter.heroku.com/) (Heroku)

## Your Daily Toolkit: Terminal and Git

The tools every backend developer uses dozens of times a day: the Linux shell and version control.

### Linux and the Command Line

core · beginner · about 10 h · https://www.internhack.in/roadmaps/tracks/backend/linux-terminal

Navigate files, manage processes, read logs and connect to servers over SSH from a Unix shell.

Almost every server you deploy to runs Linux, and most backend tooling assumes a Unix shell. You do not need to be a sysadmin, but you should feel at home in a terminal.

#### Core skills
- **Navigation and files**: `cd`, `ls -la`, `cp`, `mv`, `rm`, `mkdir -p`, `find`.
- **Reading and searching**: `cat`, `less`, `head`, `tail -f` (follow a log live), `grep -r`.
- **Pipes and redirection**: chain small tools with `|`, send output to files with `>` and `>>`. For example `grep ERROR app.log | wc -l`.
- **Permissions**: users, groups and the `rwx` bits; `chmod` and `chown`. Many "it works locally" bugs are permission bugs.
- **Processes**: `ps`, `top` or `htop`, `kill`, and how services are run by **systemd** (`systemctl status myapp`, `journalctl -u myapp`).
- **Networking**: `ssh` with key pairs, `scp`, `curl`, `ss -tlnp` to see which ports are listening.

#### Why it matters
Production incidents are debugged in a shell: tailing logs, checking disk space with `df -h`, checking memory with `free -m`, finding which process holds a port. The faster you are here, the calmer you are under pressure.

#### Pitfalls
- Running everything as root. Create a normal user and use `sudo` when needed.
- Using password SSH logins on a public server. Use keys and disable password auth.

You are ready to move on when you can SSH into a fresh server, create a user, install a package, run your app as a service and read its logs without searching for every command.

Key concepts: Filesystem navigation, Pipes, redirection and grep, Permissions and users, Processes and signals, systemd and journalctl, SSH keys and remote access, Package managers (apt, dnf), Shell scripting basics, Terminal editors (vim or nano).

Mini project: Write a bash script that checks disk usage, memory and whether your app's port is listening, and prints a one-line health summary. Schedule it with cron.

Self-check: A process is holding port 3000 and your app will not start. Which commands do you use to find and stop it?

Resources:
- [LinuxCommand.org](https://linuxcommand.org/) (LinuxCommand.org)
- [The Linux command line for beginners](https://ubuntu.com/tutorials/command-line-for-beginners) (Ubuntu)
- [GNU Bash manual](https://www.gnu.org/software/bash/manual/) (GNU)

### Version Control with Git

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/git-version-control

Track changes, branch safely, resolve conflicts and keep a clean history with Git.

Git records snapshots of your project so you can go back in time, work on features in isolation and collaborate without overwriting each other. Every professional backend team uses it.

#### The mental model
A **commit** is a snapshot plus a pointer to its parent. A **branch** is just a movable label pointing at a commit. `HEAD` is where you are now. The **staging area** (index) lets you choose exactly what goes into the next commit. Once this clicks, commands stop feeling magical.

#### Everyday workflow
- `git status`, `git add -p`, `git commit`, `git log --oneline --graph`
- `git switch -c feature/x` to branch, `git merge` or `git rebase` to integrate
- `git pull`, `git push`, and working with a remote called `origin`
- `git stash` to park unfinished work, `git restore` to discard changes

#### Resolving conflicts
Conflicts happen when two branches change the same lines. Git marks the region; you edit the file to the correct final state, stage it and continue. Small, frequent commits and short-lived branches keep conflicts rare.

#### Pitfalls
- Committing secrets such as `.env` files. Add them to `.gitignore` from day one; removing a secret from history is painful and the secret should be rotated anyway.
- Rewriting history (`rebase`, `push --force`) on branches others use.
- Giant commits with messages like "fix". Write messages that explain **why**.

You are ready to move on when you can branch, commit, rebase onto main, resolve a conflict and recover a "lost" commit with `git reflog`.

Key concepts: Commits, staging and history, Branching and merging, Rebasing, Resolving merge conflicts, .gitignore, Remotes: push, pull, fetch, reflog and undoing mistakes, Conventional commit messages.

Mini project: Create a repo, make two branches that edit the same function differently, merge them to produce a conflict, resolve it, then practice an interactive rebase to squash commits.

Self-check: What is the difference between git merge and git rebase, and when would you avoid rebasing?

Resources:
- [Pro Git (free book)](https://git-scm.com/book/en/v2) (git-scm.com)
- [Learn Git Branching](https://learngitbranching.js.org/) (learngitbranching.js.org)

### Collaborating on Hosted Repositories

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/repo-hosting

Use GitHub, GitLab or Bitbucket for pull requests, code review, issues and branch protection.

Git itself is local; a **hosting platform** gives your team a shared remote plus collaboration features. The concepts are nearly identical across platforms, so learn one well.

#### What you do on these platforms
- **Pull requests / merge requests**: propose a branch for merging, discuss it line by line and require approvals.
- **Code review**: read others' changes critically but kindly; look for correctness, clarity, tests and security, not just style.
- **Branch protection**: require passing CI and at least one review before anything reaches `main`.
- **Issues and projects**: track bugs and features, link them to PRs.
- **Forks**: contribute to projects you do not have write access to (the open source workflow).

#### A healthy team workflow
Most teams use a variant of **trunk-based development**: short-lived feature branches, small PRs, merge to `main` often, deploy from `main`. Long-running branches that drift for weeks cause painful merges.

#### Pitfalls
- Huge PRs that nobody can meaningfully review. Aim for changes a reviewer can understand in 15-20 minutes.
- Leaving CI red and merging anyway.

You are ready to move on when you have opened a PR with a clear description, responded to review comments and merged it with CI passing, ideally on an open source project.

Key concepts: GitHub, GitLab, Bitbucket, Pull requests and code review, Branch protection rules, Forking workflow, Trunk-based development.

Mini project: Fork a small open source project, fix a typo or tiny bug, and open a pull request following its contribution guide.

Self-check: Why do teams require CI to pass and a review before merging into main?

Resources:
- [GitHub Docs](https://docs.github.com/en) (GitHub)
- [GitLab Docs](https://docs.gitlab.com/) (GitLab)
- [Bitbucket Cloud support](https://support.atlassian.com/bitbucket-cloud/) (Atlassian)

## Pick One Server Language

Choose a single language and its main web framework and go deep. Concepts transfer; switching later is easy.

### JavaScript on the Server with Node.js

recommended · beginner · about 40 h · https://www.internhack.in/roadmaps/tracks/backend/nodejs

Learn Node.js, its event loop, npm and a web framework like Express or Fastify to build HTTP APIs.

**Node.js** runs JavaScript outside the browser on the V8 engine. It is our recommended first backend language because you can use one language across frontend and backend, the package ecosystem (npm) is huge and the job market is large. Pair it with **TypeScript** as soon as you are comfortable, since types catch many bugs before runtime.

#### How Node works
Node runs your JavaScript on a **single thread** with an **event loop**. I/O (network, disk, database) is non-blocking: you start an operation and continue, and a callback or `await` resumes when it finishes. This makes Node excellent for I/O-heavy APIs, but a CPU-heavy loop (image processing, big JSON parsing) blocks every other request. Offload such work to worker threads or a separate service.

#### What to learn
- Modern JavaScript: `async`/`await`, Promises, modules (ESM), destructuring, error handling.
- npm or pnpm, `package.json`, semantic versioning and lockfiles.
- A framework: **Express** (minimal, ubiquitous), **Fastify** (fast, schema-first) or **NestJS** (opinionated, structured).
- Validating input (Zod or similar), middleware, routing, and centralized error handling.

#### Pitfalls
- Unhandled promise rejections crashing the process. Always `await` or `catch`.
- Mixing CommonJS and ESM without understanding the difference.

You are ready to move on when you can build a small CRUD API with routing, validation, error handling and environment-based config, and explain why a synchronous loop hurts every user.

Key concepts: Event loop and async I/O, async/await and Promises, npm, package.json and lockfiles, TypeScript, Express, Fastify, NestJS, Input validation with Zod, Worker threads.

Mini project: Build a TypeScript Express or Fastify API for a bookmarks app with CRUD endpoints, Zod validation, a global error handler and config loaded from environment variables.

Self-check: What happens to other in-flight requests when one request handler runs a 3-second synchronous loop in Node.js?

Resources:
- [Node.js Learn](https://nodejs.org/en/learn) (Node.js)
- [Express documentation](https://expressjs.com/) (Express)
- [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html) (TypeScript)

### Python for Backend Development

alternative · beginner · about 40 h · https://www.internhack.in/roadmaps/tracks/backend/python

Use Python with Django, Flask or FastAPI to build readable, productive web services.

**Python** is prized for readability and a gentle learning curve, and it dominates data science and machine learning. If your backend will sit close to ML models or data pipelines, Python is a strong choice.

#### Frameworks
- **Django**: "batteries included". ORM, migrations, admin panel, auth and forms out of the box. Great for full products built quickly.
- **FastAPI**: modern, async, type-hint driven. Generates OpenAPI docs automatically and validates with Pydantic. Excellent for pure APIs.
- **Flask**: minimal and flexible; you pick every extension yourself.

#### What to learn
- Core language: functions, classes, comprehensions, exceptions, context managers, type hints.
- Packaging and environments: `venv`, `pip`, and a tool like **uv** or **Poetry** for dependency locking.
- Async with `asyncio` if you choose FastAPI, and when it helps versus when sync is fine.
- Running in production with **Gunicorn** or **Uvicorn** workers behind a reverse proxy.

#### Pitfalls
- Installing packages globally and breaking other projects. Always use a virtual environment.
- The **GIL** limits CPU-bound parallelism in threads; use processes or offload heavy work.

You are ready to move on when you can build and deploy a small API with validation, a database connection and automated tests in your chosen framework.

Key concepts: Core Python and type hints, Virtual environments and packaging, FastAPI, Django, Flask, Pydantic validation, asyncio, Gunicorn and Uvicorn.

Mini project: Build a FastAPI or Django REST service for a to-do list with validation, auto-generated docs and pytest tests.

Self-check: When does async in FastAPI actually improve throughput, and when does it make no difference?

Resources:
- [The Python Tutorial](https://docs.python.org/3/tutorial/) (Python.org)
- [FastAPI documentation](https://fastapi.tiangolo.com/) (FastAPI)
- [Django documentation](https://docs.djangoproject.com/) (Django)

### Go for Backend Services

alternative · beginner · about 40 h · https://www.internhack.in/roadmaps/tracks/backend/go

Learn Go's simple syntax, goroutines and standard library to build fast, easily deployed services.

**Go** was designed at Google for building networked services. It compiles to a single static binary, starts instantly, uses little memory and has concurrency built into the language. It is popular for infrastructure tools (Docker, Kubernetes and Terraform are written in Go) and high-throughput APIs.

#### Why teams pick Go
- A small language you can learn in weeks, with one standard formatting style (`gofmt`).
- **Goroutines** (very cheap threads) and **channels** make concurrent code approachable.
- A strong standard library: `net/http` alone is production-capable, and recent versions support method and path patterns in the router.

#### What to learn
- Types, structs, interfaces, slices, maps and explicit error handling (`if err != nil`).
- Modules (`go mod`), packages and project layout.
- `net/http`, `context` for cancellation and timeouts, `encoding/json`.
- Optional routers or frameworks such as **chi**, **Gin** or **Echo**, and database access with `database/sql`, **pgx** or **sqlc**.

#### Pitfalls
- Leaking goroutines that wait forever on a channel. Always have a way to stop them, usually via `context`.
- Ignoring returned errors; the compiler will not force you to handle them well.

You are ready to move on when you can build a JSON API with `net/http`, graceful shutdown, request timeouts via `context` and a Postgres connection.

Key concepts: Structs, interfaces and errors, Goroutines and channels, context package, net/http standard library, Go modules, chi, Gin or Echo, pgx and sqlc.

Mini project: Build a URL shortener in Go using only the standard library router, with graceful shutdown on SIGTERM and per-request timeouts.

Self-check: How does the context package help you avoid wasted work when a client disconnects?

Resources:
- [A Tour of Go](https://go.dev/tour/) (go.dev)
- [Go documentation](https://go.dev/doc/) (go.dev)
- [Go by Example](https://gobyexample.com/) (gobyexample.com)

### Java and the Spring Ecosystem

alternative · beginner · about 50 h · https://www.internhack.in/roadmaps/tracks/backend/java

Build enterprise-grade services with Java, Maven or Gradle and Spring Boot.

**Java** runs a huge share of enterprise, banking and large-scale systems. The JVM is mature, fast after warm-up and extremely well instrumented. **Spring Boot** is the dominant framework and is worth learning as a unit with the language.

#### What to learn
- Modern Java (17 or newer): classes, interfaces, generics, records, collections, streams, exceptions.
- Build tools: **Maven** or **Gradle**, dependency management and project structure.
- **Spring Boot**: dependency injection, REST controllers, configuration profiles, **Spring Data JPA** for databases, Spring Security for auth.
- Concurrency: threads, executors and **virtual threads** (Java 21), which make blocking-style code scale well.

#### Why teams pick it
Strong typing, excellent tooling (IntelliJ), backward compatibility and a massive talent pool. Alternatives on the JVM include **Kotlin** (often with Spring or Ktor) and frameworks like **Quarkus** or **Micronaut** that start faster.

#### Pitfalls
- Annotation "magic": learn what Spring does for you (bean creation, proxies, transactions) or debugging becomes guesswork.
- Over-engineering with layers of interfaces nobody needs.

You are ready to move on when you can build a Spring Boot REST API with JPA, validation, a global exception handler and integration tests.

Key concepts: Modern Java language features, Maven or Gradle, Spring Boot, Spring Data JPA and Hibernate, Dependency injection, Virtual threads, Kotlin, Quarkus or Micronaut.

Mini project: Build a Spring Boot inventory API with JPA entities, validation annotations, pagination and a controller-level exception handler.

Self-check: What does Spring's @Transactional actually do, and why does calling a transactional method from inside the same class sometimes not start a transaction?

Resources:
- [Learn Java (dev.java)](https://dev.java/learn/) (Oracle)
- [Spring guides](https://spring.io/guides) (Spring)

### C# and ASP.NET Core

alternative · beginner · about 45 h · https://www.internhack.in/roadmaps/tracks/backend/csharp

Build cross-platform web APIs with C#, .NET and ASP.NET Core.

**C#** on modern **.NET** is fast, cross-platform (Linux, macOS, Windows) and open source. **ASP.NET Core** consistently ranks among the fastest mainstream web frameworks, and the tooling (Visual Studio, Rider, the `dotnet` CLI) is excellent.

#### What to learn
- The language: classes, records, interfaces, generics, LINQ, nullable reference types, `async`/`await` (C# popularized this pattern).
- The `dotnet` CLI, project files and NuGet packages.
- ASP.NET Core: **Minimal APIs** or controllers, middleware pipeline, dependency injection, configuration and options.
- **Entity Framework Core** for database access and migrations.

#### Where it shines
Enterprise environments, Azure-heavy shops, games backends and teams that want strong typing with high performance.

#### Pitfalls
- Blocking on async code with `.Result` or `.Wait()`, which can cause deadlocks and thread starvation.
- Letting EF Core generate inefficient queries without checking the SQL it emits.

You are ready to move on when you can build a Minimal API with EF Core, validation, dependency-injected services and tests using `WebApplicationFactory`.

Key concepts: C# language and LINQ, dotnet CLI and NuGet, ASP.NET Core Minimal APIs, Middleware and dependency injection, Entity Framework Core, async/await pitfalls.

Mini project: Build an ASP.NET Core Minimal API for a notes app with EF Core on SQLite, then switch the provider to PostgreSQL through configuration only.

Self-check: Why is calling .Result on a Task inside a request handler considered dangerous?

Resources:
- [C# documentation](https://learn.microsoft.com/en-us/dotnet/csharp/) (Microsoft Learn)
- [ASP.NET Core documentation](https://learn.microsoft.com/en-us/aspnet/core/) (Microsoft Learn)

### PHP and Laravel

alternative · beginner · about 40 h · https://www.internhack.in/roadmaps/tracks/backend/php

Use modern PHP with Laravel or Symfony, the stack behind a large share of the web.

**PHP** powers a very large part of the web, including WordPress, and modern PHP (8.x) is a far cry from its reputation: it has types, enums, attributes, JIT compilation and a strong package manager in **Composer**.

#### Frameworks
- **Laravel**: elegant, productive and full-featured. Eloquent ORM, migrations, queues, auth scaffolding and a large ecosystem.
- **Symfony**: component-based and very structured; many other projects (including Laravel) use its components.

#### What to learn
- PHP 8 syntax, strict types, classes, interfaces, namespaces and Composer autoloading.
- The request lifecycle: traditionally each request starts fresh (share-nothing), which makes scaling simple but means caching and connection reuse work differently than in long-running servers.
- Running with **PHP-FPM** behind Nginx, or newer long-running servers like **FrankenPHP** or Laravel Octane.

#### Pitfalls
- Following old tutorials that build SQL with string concatenation. Always use prepared statements or the ORM.
- Mixing HTML and business logic in one file.

You are ready to move on when you can build a Laravel or Symfony API with migrations, validation, auth and a queue-backed job.

Key concepts: Modern PHP 8 features, Composer and autoloading, Laravel, Symfony, PHP-FPM with Nginx, Eloquent ORM.

Mini project: Build a Laravel API for an event RSVP system with migrations, form request validation and an email notification sent from a queued job.

Self-check: How does PHP's share-nothing request model affect how you cache data compared with a long-running Node or Go server?

Resources:
- [PHP manual](https://www.php.net/manual/en/) (php.net)
- [Laravel documentation](https://laravel.com/docs) (Laravel)
- [PHP The Right Way](https://phptherightway.com/) (phptherightway.com)

### Ruby on Rails

alternative · beginner · about 40 h · https://www.internhack.in/roadmaps/tracks/backend/ruby

Build products quickly with Ruby and Rails' convention-over-configuration approach.

**Ruby** is a expressive language designed for developer happiness, and **Ruby on Rails** is the framework that popularized conventions many others copied: MVC structure, migrations, an ActiveRecord ORM and generators. Startups and companies like Shopify and GitHub have run large Rails codebases.

#### What to learn
- Ruby basics: blocks, iterators, symbols, modules, and its object model where everything is an object.
- **Bundler** and gems for dependencies.
- Rails: routing, controllers, **ActiveRecord** models, associations, validations, migrations and **Active Job** for background work.
- API-only mode (`rails new app --api`) if you are building a JSON backend.

#### Why teams pick it
Very high productivity for CRUD-heavy products. Following the conventions means a new developer can find their way around any Rails app.

#### Pitfalls
- N+1 queries hidden behind ActiveRecord associations; learn `includes` early.
- "Fat models" that grow into thousands of lines. Extract service objects when logic gets complex.

You are ready to move on when you can build a Rails API with associations, validations, background jobs and request specs.

Key concepts: Ruby language basics, Bundler and gems, Rails MVC and routing, ActiveRecord, Active Job and Sidekiq, RSpec.

Mini project: Build a Rails API-only app for a book club with users, books and reviews, including eager loading to avoid N+1 queries.

Self-check: What does Rails' includes method do, and what problem does it prevent?

Resources:
- [Ruby documentation](https://www.ruby-lang.org/en/documentation/) (ruby-lang.org)
- [Ruby on Rails Guides](https://guides.rubyonrails.org/) (Rails)

### Rust for High-Performance Backends

alternative · intermediate · about 60 h · https://www.internhack.in/roadmaps/tracks/backend/rust

Use Rust with Axum or Actix for memory-safe, very fast services, accepting a steeper learning curve.

**Rust** gives you C-level performance with memory safety enforced at compile time through its **ownership and borrowing** rules. There is no garbage collector, so latency is predictable. It is increasingly used for performance-critical services, proxies, databases and tooling.

#### What to learn
- Ownership, borrowing and lifetimes: the concepts that make Rust different. Expect to fight the compiler at first; it is teaching you.
- `Result` and `Option` for error handling, pattern matching, traits and generics.
- **Cargo** for builds and dependencies.
- Async Rust with the **Tokio** runtime, and a web framework such as **Axum** (recommended) or **Actix Web**.
- Database access with **sqlx** (compile-time checked queries) or **Diesel**.

#### Honest trade-offs
Rust is the hardest option on this list for beginners. It is a great second backend language, or a first one if you already program and want to go deep on systems concepts. Iteration speed is slower than in dynamic languages.

#### Pitfalls
- Reaching for `clone()` and `unwrap()` everywhere to silence the compiler. Fine while learning, dangerous in production.

You are ready to move on when you can build an Axum API with shared state, sqlx queries and proper error types that map to HTTP responses.

Key concepts: Ownership and borrowing, Result, Option and error handling, Cargo and crates, Tokio async runtime, Axum, Actix Web, sqlx.

Mini project: Build a small Axum service that stores and lists notes in PostgreSQL via sqlx, with a custom error type implementing IntoResponse.

Self-check: Why does Rust not need a garbage collector, and what does that mean for tail latency?

Resources:
- [The Rust Programming Language](https://doc.rust-lang.org/book/) (rust-lang.org)
- [Learn Rust](https://www.rust-lang.org/learn) (rust-lang.org)
- [Tokio tutorial](https://tokio.rs/tokio/tutorial) (Tokio)

## Storing Data Relationally

Model data in tables, query it with SQL and run a real relational database engine.

### The Relational Model

core · beginner · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/relational-model

Understand tables, rows, primary and foreign keys, constraints and relationships before writing any SQL.

A relational database stores data in **tables** (relations). Each **row** is one record and each **column** has a type. The power comes from linking tables through keys instead of duplicating data.

#### Key ideas
- **Primary key**: a column (or set of columns) that uniquely identifies a row, such as `id`. Common choices are auto-incrementing integers or UUIDs.
- **Foreign key**: a column that references another table's primary key, for example `orders.user_id -> users.id`. The database enforces that the referenced row exists.
- **Relationships**: one-to-one, one-to-many (a user has many orders) and many-to-many (students and courses, modeled with a **join table**).
- **Constraints**: `NOT NULL`, `UNIQUE`, `CHECK` and foreign keys let the database guard your data even when application code has bugs.

#### Why relational first
Most business data (users, orders, payments, bookings) is naturally relational, and relational databases give you strong consistency, flexible querying and decades of tooling. Start here and add other stores when you have a concrete reason.

#### Pitfalls
- Skipping constraints "for flexibility". Bad data is far more expensive than a failed insert.
- Storing comma-separated lists in a column instead of using a related table.

You are ready to move on when you can draw an entity-relationship diagram for a small app (for example a blog with users, posts, comments and tags) and name every key and constraint.

Key concepts: Tables, rows and column types, Primary keys (serial vs UUID), Foreign keys and referential integrity, One-to-many and many-to-many, Constraints: NOT NULL, UNIQUE, CHECK, ER diagrams.

Mini project: Design the schema for a library system (members, books, copies, loans) as an ER diagram, then write the CREATE TABLE statements with all keys and constraints.

Self-check: How would you model tags on blog posts, and why not store them as a comma-separated string?

Resources:
- [PostgreSQL tutorial: the SQL language](https://www.postgresql.org/docs/current/tutorial.html) (PostgreSQL)
- [freeCodeCamp: database design articles](https://www.freecodecamp.org/news/tag/database/) (freeCodeCamp)

### Writing SQL Queries

core · beginner · about 12 h · https://www.internhack.in/roadmaps/tracks/backend/sql-querying

Read and write data with SELECT, JOIN, GROUP BY, subqueries and window functions.

SQL is the language for talking to relational databases, and it is one of the most durable skills in software. Even if you use an ORM daily, you need to read and write SQL to debug and optimize.

#### Build up in this order
1. **CRUD**: `SELECT ... FROM ... WHERE`, `INSERT`, `UPDATE`, `DELETE`. Always double-check the `WHERE` clause on updates and deletes.
2. **Sorting and limiting**: `ORDER BY`, `LIMIT`, `OFFSET`.
3. **Joins**: `INNER JOIN` (only matches), `LEFT JOIN` (keep all rows from the left even without a match). These answer most real questions.
4. **Aggregation**: `COUNT`, `SUM`, `AVG`, `GROUP BY` and `HAVING` (filter after grouping).
5. **Subqueries and CTEs**: `WITH recent AS (...) SELECT ...` makes complex queries readable.
6. **Window functions**: `ROW_NUMBER()`, `RANK()`, running totals with `SUM() OVER (...)`.
7. **Upserts**: `INSERT ... ON CONFLICT DO UPDATE` in PostgreSQL.

#### Safety
Never build SQL by concatenating user input. Use **parameterized queries** (`WHERE email = $1`) so the driver sends data separately from the query text. This prevents SQL injection.

#### Pitfalls
- `NULL` is not equal to anything, including `NULL`. Use `IS NULL`.
- `SELECT *` in application code hides which columns you depend on and fetches more than needed.

You are ready to move on when you can answer "top 5 customers by revenue last month, including customers with zero orders" in a single query.

Key concepts: SELECT, INSERT, UPDATE, DELETE, INNER and LEFT JOIN, GROUP BY and HAVING, Subqueries and CTEs, Window functions, Upserts, Parameterized queries, NULL semantics.

Mini project: Load a sample dataset (for example the PostgreSQL Pagila or a Kaggle CSV) and write 15 progressively harder queries, ending with window functions and CTEs.

Self-check: Why does a LEFT JOIN followed by a WHERE condition on the right table sometimes behave like an INNER JOIN?

Resources:
- [SQLBolt interactive lessons](https://sqlbolt.com/) (SQLBolt)
- [PostgreSQL: Queries](https://www.postgresql.org/docs/current/queries.html) (PostgreSQL)
- [Select Star SQL](https://selectstarsql.com/) (selectstarsql.com)

### PostgreSQL

recommended · beginner · about 10 h · https://www.internhack.in/roadmaps/tracks/backend/postgresql

Run, configure and use PostgreSQL, a powerful open source relational database and our default pick.

**PostgreSQL** is our recommended relational database. It is open source, standards-compliant, extremely reliable and has features that let one database cover many needs: JSONB columns, full-text search, arrays, geospatial data (PostGIS), and extensions such as `pgvector` for embeddings.

#### What to learn
- Install it locally (or run it in Docker) and use `psql`: `\l`, `\c`, `\dt`, `\d table`.
- Roles and permissions: create an application user that owns only its database, never connect your app as the superuser.
- Data types worth knowing: `text`, `integer`/`bigint`, `numeric` for money, `timestamptz` for time, `uuid`, `jsonb`, `boolean`.
- Connection strings, SSL mode and how your driver connects.
- Backups with `pg_dump` and restoring with `pg_restore`, and why managed services (RDS, Cloud SQL, Neon, Supabase) are popular.

#### Why PostgreSQL
It handles workloads from a hobby app to large production systems, and skills transfer directly to managed Postgres offerings everywhere.

#### Pitfalls
- Using `timestamp` without time zone and then fighting time zone bugs. Prefer `timestamptz`.
- Using floating point for money.
- Never testing restores. A backup you have not restored is a hope, not a backup.

You are ready to move on when you can create a database and app role, load a schema, take a dump and restore it into a fresh instance.

Key concepts: psql command-line client, Roles and privileges, Data types: timestamptz, numeric, jsonb, pg_dump and pg_restore, Extensions (PostGIS, pgvector), Managed Postgres services, Full-text search in Postgres.

Mini project: Run PostgreSQL in Docker, create an app role with limited privileges, load your library schema, and script a nightly pg_dump that you verify by restoring into a second container.

Self-check: Why should your application not connect to PostgreSQL as the postgres superuser?

Resources:
- [PostgreSQL documentation](https://www.postgresql.org/docs/) (PostgreSQL)
- [PostgreSQL Tutorial](https://www.postgresqltutorial.com/) (postgresqltutorial.com)

### MySQL, SQLite and Other Engines

alternative · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/other-relational-engines

Know the other common relational engines and how they differ from PostgreSQL, in case your job uses one.

Relational databases share SQL and core concepts, so once you know one, switching is mostly about learning differences. Pick one of these instead of PostgreSQL only if your team or target job uses it.

- **MySQL**: hugely popular, especially with PHP and in older web stacks. Use the **InnoDB** engine (the default) for transactions. Watch for differences in default isolation level (REPEATABLE READ), case sensitivity and older lax modes that silently truncated data; enable strict SQL mode.
- **MariaDB**: a community fork of MySQL, largely compatible, with its own features.
- **SQLite**: an embedded database in a single file, no server process. Perfect for local development, tests, mobile apps, CLI tools and even small production sites. Limited concurrent writes.
- **Microsoft SQL Server**: common in enterprise and .NET shops, uses the T-SQL dialect.
- **Oracle Database**: common in large enterprises and finance, with its own PL/SQL dialect and licensing costs.

#### How to switch engines smoothly
Learn the dialect differences: auto-increment syntax, upsert syntax, string functions, date handling and pagination. ORMs smooth over many of these but not all.

#### Pitfalls
- Assuming behavior is identical. Test migrations and edge cases on the engine you run in production, not just SQLite in tests.

You are ready to move on when you can take a schema written for PostgreSQL and port it to one other engine, noting every change you needed.

Key concepts: MySQL (InnoDB), MariaDB, SQLite, Microsoft SQL Server, Oracle Database, SQL dialect differences.

Mini project: Port a small PostgreSQL schema and five queries to MySQL and SQLite, documenting each syntax or behavior difference you hit.

Self-check: When is SQLite a perfectly good production database, and when is it the wrong choice?

Resources:
- [MySQL documentation](https://dev.mysql.com/doc/) (Oracle)
- [SQLite documentation](https://www.sqlite.org/docs.html) (SQLite)
- [SQL Server documentation](https://learn.microsoft.com/en-us/sql/) (Microsoft Learn)

### Schema Design and Normalization

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/schema-design-normalization

Structure tables to avoid anomalies, and know when deliberate denormalization pays off.

**Normalization** is the practice of organizing tables so each fact is stored in exactly one place. It prevents **anomalies**: updating a customer's address in one order row but not another, or being unable to store a product until someone orders it.

#### The normal forms, practically
- **1NF**: each column holds one atomic value; no repeating groups or lists in a cell.
- **2NF**: in tables with composite keys, every non-key column depends on the whole key.
- **3NF**: non-key columns depend only on the key, not on other non-key columns. (If `zip` determines `city`, `city` does not belong in the orders table.)

For most applications, aiming for 3NF and then making deliberate exceptions is the right default.

#### Denormalization
Sometimes you intentionally duplicate data for read speed or simplicity: storing a `comment_count` on posts, or copying the price onto an order line (which is actually correct, because the order must remember the price at purchase time). Denormalize with intent and keep the copies in sync through transactions, triggers or events.

#### Practical design habits
- Name consistently (`snake_case`, singular or plural, pick one).
- Add `created_at` and `updated_at` to most tables.
- Decide on **soft deletes** (`deleted_at`) versus hard deletes up front.

You are ready to move on when you can take a messy spreadsheet-style table and split it into a normalized schema, then justify one deliberate denormalization.

Key concepts: Update, insert and delete anomalies, First, second and third normal form, Deliberate denormalization, Naming conventions, Soft deletes vs hard deletes, BCNF and higher forms.

Mini project: Take a flat CSV of orders (customer name, address, product, price, quantity in each row) and normalize it into customers, products, orders and order_items with a migration script that moves the data.

Self-check: Why is copying a product's price into order_items not a normalization violation in practice?

Resources:
- [Database normalization (Wikipedia)](https://en.wikipedia.org/wiki/Database_normalization) (Wikipedia)
- [PostgreSQL: Data Definition](https://www.postgresql.org/docs/current/ddl.html) (PostgreSQL)

## Databases in Real Applications

The database skills that separate a demo from a production system: ORMs, transactions, performance and migrations.

### ORMs and Query Builders

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/orms-query-builders

Use an ORM or query builder productively while staying aware of the SQL it generates.

An **ORM** (Object-Relational Mapper) maps tables to classes or objects so you can write `user.orders` instead of SQL. A **query builder** is lighter: it builds SQL with code but keeps you close to the query. Both save time and reduce injection risk; both can hide expensive queries.

#### Common choices
- Node/TypeScript: **Prisma**, **Drizzle**, TypeORM, Knex (query builder), Kysely.
- Python: **SQLAlchemy**, Django ORM.
- Java: Hibernate / JPA. C#: Entity Framework Core. Ruby: ActiveRecord. Go: sqlc, GORM.

#### The N+1 problem
The classic ORM trap: load 50 posts (1 query), then access `post.author` in a loop, which triggers 50 more queries. The fix is **eager loading** (`include`, `joinedload`, `includes`) or a join. Always enable query logging in development so you see this happen.

#### Good habits
- Log SQL in development and read it.
- Select only the fields you need.
- Drop to raw SQL for complex reports; every good ORM allows it with parameters.
- Keep the ORM in a data access layer so business logic does not depend on its quirks.

#### Pitfalls
- Treating the ORM as a way to never learn SQL. You will eventually need to debug what it emits.

You are ready to move on when you can spot and fix an N+1 query by reading the query log, and write the same query in both your ORM and raw SQL.

Key concepts: Active Record vs Data Mapper, Prisma or Drizzle (Node), SQLAlchemy, Hibernate, EF Core, Query builders (Knex, Kysely), N+1 queries and eager loading, Query logging, Raw SQL escape hatches.

Mini project: Build an endpoint that lists 50 posts with authors and comment counts. First write it naively and count the queries in the log, then fix it to use at most 2 queries.

Self-check: How would you detect an N+1 query problem in an app you did not write?

Resources:
- [Prisma documentation](https://www.prisma.io/docs) (Prisma)
- [SQLAlchemy documentation](https://docs.sqlalchemy.org/) (SQLAlchemy)
- [Drizzle ORM documentation](https://orm.drizzle.team/docs/overview) (Drizzle)

### Transactions, ACID and Isolation

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/transactions-acid

Group changes atomically and understand what each isolation level does and does not protect you from.

A **transaction** groups several statements so they succeed or fail together. Transferring money is the textbook case: debit one account and credit another, or do neither.

#### ACID
- **Atomicity**: all or nothing. On error you `ROLLBACK`.
- **Consistency**: constraints hold before and after.
- **Isolation**: concurrent transactions do not see each other's half-finished work (to a configurable degree).
- **Durability**: once committed, data survives a crash (thanks to the write-ahead log).

#### Isolation levels and anomalies
Concurrency causes anomalies: **dirty reads** (seeing uncommitted data), **non-repeatable reads** (a row changes between two reads), **phantoms** (new rows appear in a range) and **lost updates / write skew**.
- **Read Committed** (PostgreSQL default): no dirty reads, but other anomalies possible.
- **Repeatable Read**: a stable snapshot for the whole transaction.
- **Serializable**: behaves as if transactions ran one after another; the database may abort one, so you must retry.

#### Practical tools
- `SELECT ... FOR UPDATE` locks rows you intend to change.
- Atomic updates like `UPDATE stock SET qty = qty - 1 WHERE id = $1 AND qty > 0` avoid read-modify-write races.
- **Optimistic locking** with a `version` column detects conflicting edits.

#### Pitfalls
- Holding a transaction open while calling an external API. Locks are held the whole time.
- Assuming the default level prevents double-booking. It usually does not.

You are ready to move on when you can reproduce a lost update with two concurrent sessions and then fix it two different ways.

Key concepts: BEGIN, COMMIT, ROLLBACK, ACID properties, Isolation levels, Read anomalies and write skew, Row locks and SELECT FOR UPDATE, Optimistic locking, MVCC internals, Retrying serialization failures.

Mini project: Build a seat-booking endpoint, write a script that fires 50 concurrent booking requests for the last seat, prove overbooking happens, then fix it with row locks or an atomic conditional update.

Self-check: Two requests read stock = 1 and both decrement it. Which isolation level or query pattern prevents this in PostgreSQL?

Resources:
- [PostgreSQL: Transaction Isolation](https://www.postgresql.org/docs/current/transaction-iso.html) (PostgreSQL)
- [PostgreSQL: Concurrency Control](https://www.postgresql.org/docs/current/mvcc.html) (PostgreSQL)

### Indexes and Query Performance

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/indexes-query-performance

Make queries fast with the right indexes and learn to read query plans and profile slow queries.

An **index** is a separate data structure (usually a **B-tree**) that lets the database find rows without scanning the whole table, much like a book's index. Indexes make reads faster and writes slightly slower, and they use disk and memory.

#### Choosing indexes
- Index columns used in `WHERE`, `JOIN` and `ORDER BY` on large tables.
- **Composite indexes** follow the leftmost-prefix rule: an index on `(user_id, created_at)` helps `WHERE user_id = ?` and `WHERE user_id = ? ORDER BY created_at`, but not `WHERE created_at > ?` alone.
- **Unique indexes** enforce uniqueness; **partial indexes** (`WHERE deleted_at IS NULL`) keep indexes small; **covering indexes** can answer a query without touching the table.
- Specialized types: GIN for JSONB and full-text, BRIN for huge append-only tables.

#### Reading plans
`EXPLAIN ANALYZE` runs a query and shows the plan: sequential scans, index scans, join strategies, estimated versus actual rows. A big gap between estimated and actual rows often means stale statistics.

#### Finding slow queries
Enable `pg_stat_statements` (or your engine's slow query log) to see which queries consume the most total time. Optimize the top few; that is where the wins are.

#### Pitfalls
- Wrapping an indexed column in a function (`WHERE lower(email) = ...`) so the index cannot be used, unless you create an expression index.
- Adding an index for every column. Measure first.

You are ready to move on when you can take a slow query, read its plan, add the right index and show the before and after timings.

Key concepts: B-tree indexes, Composite index column order, Unique, partial and covering indexes, GIN, GiST and BRIN, EXPLAIN ANALYZE, pg_stat_statements and slow query logs, Table statistics and VACUUM.

Mini project: Generate a table with 5 million rows, write three realistic slow queries, and bring each under 10 ms with appropriate indexes, documenting EXPLAIN ANALYZE output before and after.

Self-check: You have an index on (status, created_at). Which of these can use it well: WHERE status = 'paid', WHERE created_at > now() - interval '1 day', or both?

Resources:
- [Use The Index, Luke](https://use-the-index-luke.com/) (Markus Winand)
- [PostgreSQL: Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html) (PostgreSQL)
- [PostgreSQL: Indexes](https://www.postgresql.org/docs/current/indexes.html) (PostgreSQL)

### Schema Migrations

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/schema-migrations

Evolve your database schema safely with versioned migrations, including on large live tables.

A **migration** is a versioned script that changes the schema (and sometimes data) from one state to the next. Migrations live in your repo, run in order, and let every environment (your laptop, CI, staging, production) reach the same schema reproducibly.

#### Tools
Most ORMs include a migration tool (Prisma Migrate, Django migrations, Alembic for SQLAlchemy, EF Core migrations, Rails migrations). Standalone options include **Flyway**, **Liquibase**, **golang-migrate** and **dbmate**.

#### Zero-downtime changes
During a deploy, old and new versions of your code run at the same time, so each migration must be compatible with both. The **expand and contract** pattern handles risky changes:
1. **Expand**: add the new column or table (nullable, no heavy default).
2. Deploy code that writes to both old and new, then backfill existing rows in batches.
3. Switch reads to the new structure.
4. **Contract**: remove the old column in a later release.

#### Dangerous operations on big tables
- Adding a `NOT NULL` column with a volatile default, changing a column type, or creating an index without `CONCURRENTLY` can lock a table for minutes.
- Set a `lock_timeout` so a migration fails fast instead of blocking all traffic.

#### Pitfalls
- Editing a migration that has already run in production. Write a new one instead.
- Renaming a column in one step while old code still reads it.

You are ready to move on when you can rename a column in a live system using expand and contract with no errors during the deploy.

Key concepts: Versioned migration files, Up and down migrations, Expand and contract pattern, Batched data backfills, CREATE INDEX CONCURRENTLY, lock_timeout, Flyway, Liquibase, Alembic.

Mini project: In a sample app, rename users.name to users.full_name across three migrations and two deploys using expand and contract, with a load script running the whole time to prove zero errors.

Self-check: Why must a migration be compatible with both the old and new version of your application code?

Resources:
- [Prisma Migrate](https://www.prisma.io/docs/orm/prisma-migrate) (Prisma)
- [Alembic documentation](https://alembic.sqlalchemy.org/) (SQLAlchemy)
- [Evolutionary Database Design](https://martinfowler.com/articles/evodb.html) (Martin Fowler)

### When Databases Misbehave

recommended · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/database-failure-modes

Recognize deadlocks, lock contention, connection exhaustion, replication lag and data loss scenarios before they hit you.

Databases fail in a handful of recurring ways. Knowing them turns a scary outage into a checklist.

#### Common failure modes
- **Deadlocks**: two transactions each hold a lock the other needs. The database kills one. Fix by locking rows in a consistent order and keeping transactions short; retry the victim.
- **Lock contention**: a long transaction or migration holds a lock and hundreds of queries queue behind it. Look at `pg_stat_activity` and `pg_locks`.
- **Connection exhaustion**: each database connection costs memory, and servers have a hard limit. Many app instances with large pools hit it quickly, producing "too many connections" errors. Use a pooler such as PgBouncer.
- **Runaway queries**: a missing index or accidental cross join saturates CPU. Use `statement_timeout`.
- **Disk full**: logs, bloat or a stuck replication slot fill the disk and writes stop.
- **Data loss**: accidental `DELETE` without `WHERE`, bad migrations, or hardware failure. Backups plus **point-in-time recovery** are the safety net.

#### Defensive defaults
- Set statement and idle-in-transaction timeouts.
- Alert on connection count, replication lag, disk usage and long-running queries.
- Rehearse restores regularly.

You are ready to move on when you can deliberately cause a deadlock in two psql sessions, read the error, and explain how you would prevent it in application code.

Key concepts: Deadlocks, Lock contention and pg_stat_activity, Connection limits, Statement timeouts, Point-in-time recovery, Table bloat.

Mini project: Write a short runbook for your app's database covering how to find blocking queries, kill a runaway query, check connection usage and restore to a point in time, and test each step locally.

Self-check: Twenty app instances each have a pool of 20 connections and Postgres allows 100. What happens and how would you fix it?

Resources:
- [PostgreSQL: Explicit Locking](https://www.postgresql.org/docs/current/explicit-locking.html) (PostgreSQL)
- [PostgreSQL: Backup and Restore](https://www.postgresql.org/docs/current/backup.html) (PostgreSQL)

## Designing and Documenting APIs

Expose your backend to clients through well-designed, documented and evolvable interfaces.

### Resource-Oriented REST APIs

core · beginner · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/rest-api-design

Design JSON-over-HTTP APIs around resources, methods and status codes that clients can predict.

**REST** is an architectural style where your API exposes **resources** (users, orders, invoices) at URLs and clients act on them with standard HTTP methods. Most public and internal web APIs are "RESTful" JSON APIs, even if few follow every constraint of the original definition.

#### Designing resources
- Use nouns, plural collections: `GET /orders`, `GET /orders/42`, `POST /orders`, `PATCH /orders/42`, `DELETE /orders/42`.
- Nest only for clear ownership: `GET /users/7/orders`. Avoid deep nesting.
- For actions that do not map to CRUD, use a sub-resource: `POST /orders/42/cancel`.
- Return the right status: 201 with a `Location` header after create, 204 for no content, 404 for missing, 409 for conflicts, 422 for validation errors.

#### Consistent payloads
Pick a JSON style (camelCase or snake_case) and stick to it. Use ISO 8601 timestamps. Return errors in one shape everywhere, for example `{ "error": { "code": "VALIDATION_FAILED", "message": "...", "details": [...] } }`, or the standard **Problem Details** format (RFC 9457).

#### Beyond the basics
- **Statelessness**: each request carries everything needed (for example an auth token), which makes horizontal scaling easy.
- **HATEOAS**: responses include links to related actions. Rarely used in full, but useful to know.
- **JSON:API** is one opinionated convention for payload shape if your team wants a standard.

#### Pitfalls
- Verbs in URLs (`/getUser`) and inconsistent naming across endpoints.
- Leaking database structure directly; your API is a contract, your schema is an implementation detail.

You are ready to move on when you can design the endpoints for a small e-commerce API on paper and defend every method and status code choice.

Key concepts: Resources and URL design, Methods and status codes in practice, JSON conventions, Error format and Problem Details, Statelessness, JSON:API specification, HATEOAS.

Mini project: Build a REST API for a recipe app with collections, nested ingredients, a custom action endpoint and one consistent error format across all failures.

Self-check: A client submits an order with an invalid quantity. Which status code do you return and what does the body look like?

Resources:
- [MDN: HTTP request methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) (MDN)
- [Fielding's dissertation: REST](https://ics.uci.edu/~fielding/pubs/dissertation/top.htm) (Roy Fielding)
- [JSON:API](https://jsonapi.org/) (jsonapi.org)

### Pagination, Versioning and Rate Limits

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/api-evolution-and-limits

Handle large result sets, change APIs without breaking clients and protect them from abuse.

Once real clients depend on your API, three practical problems appear: returning large lists, changing things without breaking anyone, and stopping one client from overwhelming the service.

#### Pagination
- **Offset pagination** (`?limit=20&offset=40`) is simple but slow on deep pages and can skip or duplicate items when data changes.
- **Cursor (keyset) pagination** (`?limit=20&after=eyJpZCI6...`) uses the last seen sort key. It is stable and fast at any depth; prefer it for feeds and large tables.
- Always cap `limit` on the server.

#### Versioning
- Additive changes (new optional fields, new endpoints) are safe. Removing or renaming fields, or changing meaning, breaks clients.
- Common strategies: URL prefix (`/v1/`), a header, or date-based versions. URL versioning is the easiest to reason about.
- Deprecate with warning headers and a timeline, and measure who still calls the old version.

#### Rate limiting
Limit requests per client (API key, user or IP) with algorithms like **token bucket** or **sliding window**, usually backed by Redis so all instances share counters. Return **429 Too Many Requests** with a `Retry-After` header.

#### Idempotency
For `POST` endpoints that create payments or orders, accept an `Idempotency-Key` header and return the stored result on retries, so a network retry never charges twice.

You are ready to move on when your API has cursor pagination, a versioning policy and a Redis-backed rate limiter that returns 429 correctly under a load test.

Key concepts: Offset pagination, Cursor / keyset pagination, Breaking vs non-breaking changes, Versioning strategies, Token bucket and sliding window, 429 and Retry-After, Idempotency keys, Filtering and sorting parameters.

Mini project: Add cursor pagination, filtering and an idempotency key to a create-order endpoint, plus a per-API-key rate limiter. Test retries and throttling with a script.

Self-check: Why does offset pagination become slow and inconsistent on a busy table with millions of rows?

Resources:
- [MDN: 429 Too Many Requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (MDN)
- [Stripe API reference (pagination and idempotency examples)](https://docs.stripe.com/api) (Stripe)

### API Contracts with OpenAPI

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/openapi-docs

Describe your HTTP API in an OpenAPI document to get docs, validation, mocks and client generation.

The **OpenAPI Specification** (formerly Swagger) is a machine-readable description of an HTTP API in YAML or JSON: paths, parameters, request bodies, responses, schemas and authentication. It turns your API into a contract that both humans and tools can read.

#### What you get from it
- Interactive documentation (Swagger UI, Redoc, Scalar) that stays in sync with the code.
- Request and response validation middleware.
- Generated client SDKs and server stubs for many languages.
- Mock servers so frontend work can start before the backend is ready.
- Contract tests and breaking-change detection in CI.

#### Code-first vs design-first
- **Code-first**: annotate routes or schemas and generate the spec (FastAPI, NestJS, Fastify schemas, springdoc). Fast to start.
- **Design-first**: write the spec, review it with consumers, then implement. Better for public APIs with many clients.

Either way, publish the spec, version it with the code and check it in CI.

#### Pitfalls
- A spec that drifts from reality because it is maintained by hand and nobody tests it.
- Documenting only the happy path; document error responses too.

You are ready to move on when your API serves an OpenAPI document with request and error schemas, and you have generated a working client from it.

Key concepts: Paths, operations and schemas, Swagger UI, Redoc, Scalar, Code-first generation, Design-first workflow, Client SDK generation, Breaking-change checks in CI.

Mini project: Add an OpenAPI document to your REST API, serve interactive docs at /docs, and generate a TypeScript or Python client that a small script uses to call two endpoints.

Self-check: What are the risks of maintaining an OpenAPI file by hand, and how can CI reduce them?

Resources:
- [OpenAPI Initiative](https://www.openapis.org/) (OpenAPI Initiative)
- [OpenAPI Specification (latest)](https://spec.openapis.org/oas/latest.html) (OpenAPI Initiative)
- [Swagger documentation](https://swagger.io/docs/) (SmartBear)

### GraphQL APIs

recommended · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/graphql

Let clients ask for exactly the data they need through a typed schema, resolvers and a single endpoint.

**GraphQL** is a query language and runtime for APIs. Instead of many endpoints, you expose one endpoint and a **typed schema**. Clients send queries describing the exact shape of data they want, and the server returns just that.

#### Core concepts
- **Schema** in SDL: types, fields, `Query` (reads), `Mutation` (writes) and `Subscription` (real-time).
- **Resolvers**: functions that fetch each field's data.
- **Introspection**: clients and tools can discover the schema, which powers great developer tooling.

#### When it shines
Many client types (web, iOS, Android) with different data needs, deeply related data, and teams that want a strongly typed contract between frontend and backend.

#### Costs and pitfalls
- **N+1 in resolvers**: resolving `author` for each of 100 posts triggers 100 queries. Use the **DataLoader** pattern to batch.
- **Expensive queries**: clients can request deeply nested data. Enforce depth and complexity limits and consider persisted queries.
- **Caching** is harder than with REST because everything is a POST to one URL.
- Authorization must be applied per field or per resolver, not only per endpoint.

Popular servers include Apollo Server, GraphQL Yoga, Strawberry (Python) and graphql-java or Spring for GraphQL.

You are ready to move on when you can build a GraphQL API with queries, mutations, DataLoader batching and a query depth limit.

Key concepts: Schema definition language, Queries, mutations, subscriptions, Resolvers, DataLoader batching, Depth and complexity limits, Apollo Server or GraphQL Yoga, Federation.

Mini project: Build a GraphQL API for a blog (users, posts, comments) and prove with query logs that DataLoader reduces a nested query from 100+ database calls to 3.

Self-check: Why is HTTP caching harder with GraphQL than with REST, and what techniques help?

Resources:
- [Learn GraphQL](https://graphql.org/learn/) (GraphQL Foundation)
- [Apollo Server documentation](https://www.apollographql.com/docs/apollo-server/) (Apollo)

### gRPC and Protocol Buffers

optional · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/grpc

Build fast, strongly typed service-to-service APIs with protobuf contracts and HTTP/2 streaming.

**gRPC** is a remote procedure call framework: you define services and messages in a `.proto` file with **Protocol Buffers**, generate client and server code for many languages, and call remote methods as if they were local functions. It runs over HTTP/2 and encodes data in a compact binary format.

#### Why teams use it
- **Performance**: binary encoding and HTTP/2 multiplexing are faster and smaller than JSON over HTTP/1.1.
- **Strong contracts**: the `.proto` file is the source of truth, and generated code catches mismatches at compile time.
- **Streaming**: server streaming, client streaming and bidirectional streaming are built in.

#### Where it fits
Mostly **internal service-to-service** communication in microservice systems. Browsers cannot speak native gRPC directly; you need gRPC-Web or a JSON gateway, so public APIs usually stay REST or GraphQL.

#### Things to learn
- Proto syntax, field numbers and why you must never reuse a removed field number.
- Deadlines (timeouts) and status codes.
- Tooling like `grpcurl` and **Buf** for linting and breaking-change detection.

You are ready to move on when you have two small services talking over gRPC with a deadline set on every call.

Key concepts: Protocol Buffers syntax, Code generation, Unary and streaming RPCs, Deadlines and status codes, Backward-compatible proto changes, gRPC-Web and gateways, grpcurl and Buf.

Mini project: Create an inventory service exposing a gRPC CheckStock method and call it from an order service, including a server-streaming method for stock updates.

Self-check: Why must you never reuse the field number of a removed protobuf field?

Resources:
- [gRPC documentation](https://grpc.io/docs/) (gRPC)
- [Protocol Buffers documentation](https://protobuf.dev/) (Google)

### SOAP and Legacy Integrations

optional · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/soap-legacy-apis

Recognize SOAP, WSDL and XML-based APIs so you can integrate with older enterprise and government systems.

**SOAP** is an XML-based messaging protocol that predates REST. Services describe themselves with a **WSDL** file, messages are wrapped in XML envelopes, and standards like WS-Security add signing and encryption. You will rarely build new SOAP services, but banks, payment networks, insurers, airlines and government systems still expose them.

#### What you need to know
- How to read a WSDL: services, operations, and message types.
- Using a client generator or library for your language (for example `zeep` in Python or `soap` on npm) instead of building XML by hand.
- Handling XML namespaces, faults (SOAP's error format) and strict schemas.

#### Integration tips
- Wrap the SOAP client behind your own small interface so the rest of your code never sees XML.
- Log requests and responses (with secrets redacted); SOAP errors are often cryptic.
- Expect slow, rate-limited endpoints and add timeouts and retries.

#### Security note
XML parsers can be vulnerable to **XXE (XML External Entity)** attacks. Disable external entity resolution in any parser handling untrusted XML.

You are ready to move on when you can call a public SOAP test service from your language and map its response to a plain object.

Key concepts: SOAP envelopes and faults, WSDL, Generated SOAP clients, XXE protection, WS-Security.

Mini project: Write an adapter module that calls a public SOAP service (for example a country info or number conversion service) and exposes its result through one of your REST endpoints.

Self-check: Why wrap a third-party SOAP client behind your own interface rather than calling it throughout your codebase?

Resources:
- [W3C SOAP specifications](https://www.w3.org/TR/soap/) (W3C)
- [OWASP XXE Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html) (OWASP)

## Who Is Calling and What Can They Do

Authentication proves identity; authorization decides permissions. Get both right with proven mechanisms.

### Sessions and Cookies

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/sessions-cookies

Implement login with server-side sessions and secure cookie settings, the classic and still excellent approach.

HTTP is stateless, so after a user logs in the server needs a way to recognize them on the next request. The classic approach: create a **session** (a record on the server, often in Redis or the database), and send the browser a **cookie** containing a random, unguessable session id. The browser sends it back automatically on each request.

#### Cookie attributes that matter
- `HttpOnly`: JavaScript cannot read the cookie, limiting damage from XSS.
- `Secure`: only sent over HTTPS.
- `SameSite=Lax` or `Strict`: not sent on most cross-site requests, a strong defense against **CSRF**.
- `Max-Age` / `Expires`, `Path` and `Domain`: control lifetime and scope.

#### Session lifecycle
- **Regenerate** the session id at login to prevent session fixation.
- Expire sessions after inactivity and absolutely after some maximum.
- On logout, delete the server-side session, not just the cookie.

#### Why sessions are a great default
They are simple, revocable instantly (delete the record), and keep sensitive data on the server. For a typical web app with its own frontend, sessions are often a better choice than JWTs.

#### Pitfalls
- Storing sessions in process memory, which breaks as soon as you run two instances.
- Using cookies for cross-site APIs without understanding CORS credentials and SameSite.

You are ready to move on when you can build login and logout with Redis-backed sessions and explain each cookie attribute you set.

Key concepts: Stateful sessions, HttpOnly, Secure, SameSite, Session stores (Redis, database), Session fixation and regeneration, CSRF protection, Remember-me and expiry.

Mini project: Add email and password login to an API using Redis-backed sessions, with session regeneration at login, an idle timeout and a logout-everywhere endpoint.

Self-check: How does SameSite=Lax help against CSRF, and what cases does it not cover?

Resources:
- [MDN: Using HTTP cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) (MDN)
- [OWASP Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html) (OWASP)

### Token-Based Auth and JWT

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/token-auth-jwt

Use signed tokens such as JWTs for APIs and mobile clients, and understand their trade-offs versus sessions.

With **token-based authentication**, the client holds a token and sends it in the `Authorization: Bearer <token>` header. A **JSON Web Token (JWT)** is a popular format: a header, a JSON payload of **claims** (`sub`, `exp`, `iat`, roles) and a signature, base64url-encoded and joined with dots.

#### How verification works
The server signs the token with a secret (HS256) or a private key (RS256, ES256). Any service with the secret or public key can verify it without a database lookup. That makes JWTs handy across multiple services and for mobile or third-party API clients.

#### The trade-offs
- **Revocation is hard**: a stolen token is valid until it expires. Keep **access tokens short-lived** (5-15 minutes) and use a longer-lived **refresh token** that is stored server-side and can be revoked and rotated.
- **Payload is readable**: signed does not mean encrypted. Never put secrets or sensitive personal data in claims.
- **Storage in browsers**: tokens in `localStorage` are exposed to XSS. For browser apps, an HttpOnly cookie is often safer.

#### Verification checklist
Validate the signature, pin the allowed algorithms (reject `none`), check `exp`, `nbf`, `iss` and `aud`, and use a well-maintained library.

#### Also know
Opaque API keys for server-to-server access, and **PASETO** as a stricter token format.

You are ready to move on when you can implement access plus refresh tokens with rotation and explain how you would log out a user whose access token has not expired yet.

Key concepts: JWT structure and claims, HS256 vs RS256 signing, Access and refresh tokens, Refresh token rotation, Token storage in browsers, API keys, PASETO.

Mini project: Build an auth service that issues 10-minute access tokens and rotating refresh tokens stored hashed in the database, with reuse detection that revokes the whole token family.

Self-check: Why is a JWT that lives for 30 days risky, and what design reduces that risk?

Resources:
- [Introduction to JSON Web Tokens](https://jwt.io/introduction) (jwt.io)
- [RFC 7519: JSON Web Token](https://datatracker.ietf.org/doc/html/rfc7519) (IETF)
- [OWASP JWT Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html) (OWASP)

### OAuth 2.0 and OpenID Connect

core · intermediate · about 7 h · https://www.internhack.in/roadmaps/tracks/backend/oauth2-oidc

Delegate access and add 'Sign in with Google/GitHub' correctly using standard flows.

**OAuth 2.0** is a framework for **delegated authorization**: letting an app access a user's resources on another service (read their GitHub repos, their Google Calendar) without ever seeing their password. **OpenID Connect (OIDC)** is a thin identity layer on top of OAuth 2.0 that adds an **ID token** (a JWT describing who the user is), which is what powers "Sign in with Google".

#### Roles
The **resource owner** (the user), the **client** (your app), the **authorization server** (Google, Auth0, Keycloak) and the **resource server** (the API holding the data).

#### The flow to know: Authorization Code with PKCE
1. Your app redirects the user to the authorization server with `client_id`, requested `scope`, `redirect_uri`, a random `state` and a PKCE code challenge.
2. The user logs in and consents.
3. The server redirects back with a short-lived **code**.
4. Your backend exchanges the code (plus the PKCE verifier) for tokens.

Other grants: **client credentials** for machine-to-machine calls. The implicit and password grants are deprecated.

#### Build or buy
Identity is easy to get subtly wrong. Many teams use a provider (Auth0, Clerk, Cognito, Firebase Auth) or self-hosted **Keycloak** instead of writing their own authorization server. You should still understand the flow to integrate and debug it.

#### Pitfalls
- Skipping `state` validation, enabling CSRF on the login flow.
- Accepting ID tokens without checking `iss`, `aud` and signature.

You are ready to move on when you have implemented "Sign in with GitHub or Google" end to end and can explain each redirect and parameter.

Key concepts: OAuth roles and scopes, Authorization code flow with PKCE, Client credentials grant, OpenID Connect and ID tokens, Social login providers, Keycloak, Auth0, Cognito, Token introspection.

Mini project: Add Sign in with GitHub to your app using the authorization code flow with PKCE, linking the external identity to a local user record.

Self-check: What is the difference between an OAuth access token and an OIDC ID token, and which one should your API accept?

Resources:
- [OAuth 2.0](https://oauth.net/2/) (oauth.net)
- [OpenID Connect Core specification](https://openid.net/specs/openid-connect-core-1_0.html) (OpenID Foundation)
- [OAuth 2.0 Simplified](https://www.oauth.com/) (Aaron Parecki)

### SAML and Enterprise Single Sign-On

optional · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/saml-enterprise-sso

Understand SAML-based SSO so your product can plug into corporate identity providers.

**SAML 2.0** is an XML-based standard for single sign-on that predates OIDC and is still the norm in large companies. When a business customer says "we need SSO with Okta or Microsoft Entra ID", they often mean SAML (or OIDC).

#### How it works
- The **Identity Provider (IdP)**, such as Okta or Entra ID, authenticates users.
- Your app is the **Service Provider (SP)**.
- The user is redirected to the IdP, logs in, and the IdP posts a **signed SAML assertion** (XML) back to your app's Assertion Consumer Service URL. You verify the signature and read attributes like email and groups.
- Configuration is exchanged via **metadata** XML documents containing URLs and certificates.

#### Related enterprise features
**SCIM** for automatically provisioning and deprovisioning users, and mapping IdP groups to your app's roles.

#### Practical advice
Do not hand-roll SAML parsing; XML signature validation has a long history of vulnerabilities. Use a mature library or an identity platform that supports SAML for you.

You are ready to move on when you can configure a free developer IdP account to log into a sample app via SAML and explain what is inside the assertion.

Key concepts: Identity Provider vs Service Provider, SAML assertions and signatures, SP and IdP metadata, SCIM provisioning, Okta and Microsoft Entra ID.

Mini project: Integrate a sample app with a free Okta or Auth0 developer tenant using SAML, and map an IdP group to an admin role in your app.

Self-check: Why is writing your own SAML signature validation a bad idea?

Resources:
- [SAML (Wikipedia)](https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language) (Wikipedia)
- [OASIS SAML technical overview](https://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html) (OASIS)

### Authorization: Roles and Permissions

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/authorization-models

Decide what an authenticated user may do with RBAC, ownership checks and attribute-based rules.

Authentication tells you **who** someone is. **Authorization** decides **what they can do**. Broken access control is the number one risk in the OWASP Top 10, usually because a check was forgotten, not because the model was wrong.

#### Common models
- **Ownership checks**: a user can edit only their own resources. Always filter by owner in the query (`WHERE id = $1 AND user_id = $2`) instead of loading by id alone.
- **RBAC (role-based)**: users get roles (admin, editor, viewer) and roles grant permissions (`post:publish`). Simple and widely understood.
- **ABAC (attribute-based)**: rules evaluate attributes of the user, resource and context ("managers can approve expenses under 1000 in their own department").
- **ReBAC (relationship-based)**: permissions follow relationships, like Google Drive sharing. Tools include OpenFGA and SpiceDB, based on Google's Zanzibar paper.
- **Multi-tenancy**: every query scoped to the current tenant, ideally enforced centrally (or with PostgreSQL row-level security).

#### Implementation habits
- Centralize checks in middleware or a policy layer, not scattered `if` statements.
- Deny by default.
- Check permissions on the server for every request, even if the UI hides the button.
- Write tests that try to access other users' data.

#### Pitfalls
- **IDOR** (insecure direct object reference): `GET /invoices/1043` returns someone else's invoice because only authentication was checked.

You are ready to move on when your app has roles, ownership checks and tests proving a user cannot read or modify another user's data.

Key concepts: Authentication vs authorization, Ownership checks and IDOR, RBAC, ABAC and policy engines, ReBAC (OpenFGA, SpiceDB), Multi-tenant isolation, PostgreSQL row-level security.

Mini project: Add RBAC to a project management API (owner, member, viewer per project) enforced in a policy module, plus tests that attempt cross-tenant access and must fail.

Self-check: Your UI hides the delete button from viewers. Why is that not authorization, and where must the real check live?

Resources:
- [OWASP Authorization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html) (OWASP)
- [OpenFGA documentation](https://openfga.dev/docs) (OpenFGA)

## Defending Your Backend

Protect users and data: store secrets and passwords properly, encrypt traffic and close the common holes.

### Storing Passwords and Hashing

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/password-hashing

Use slow, salted password hashes like Argon2id or bcrypt, and know why fast hashes like MD5 and SHA are wrong for passwords.

Never store passwords, not even encrypted. Store a **password hash**: a one-way transformation that lets you verify a login attempt but not recover the original.

#### Fast hashes vs password hashes
- **MD5** and **SHA-1** are broken for security and must not be used.
- **SHA-256** and **SHA-3** are fine for integrity checks, signatures and checksums, but they are designed to be **fast**. An attacker with a GPU can try billions of guesses per second against a leaked SHA-256 hash.
- **Password hashing functions** are deliberately slow and tunable: **Argon2id** (the current recommendation), **scrypt** and **bcrypt**. They include a random **salt** per password so identical passwords produce different hashes and precomputed rainbow tables are useless.

#### Practical rules
- Use your language's well-known library (`argon2`, `bcrypt`) and its verify function, which compares in constant time.
- Tune the cost so hashing takes roughly 100-500 ms on your hardware, and raise it over time; rehash on login when parameters change.
- bcrypt truncates input at 72 bytes; be aware if you allow very long passphrases.
- Rate-limit login attempts and consider checking passwords against known breach lists.

#### Related: HMAC and encryption
Use **HMAC-SHA256** to sign data such as webhook payloads, and authenticated encryption (AES-GCM) via a vetted library when you must decrypt data later. Never invent your own crypto.

You are ready to move on when you can explain why SHA-256 is wrong for passwords but right for file checksums, and your app stores Argon2id or bcrypt hashes only.

Key concepts: Argon2id, bcrypt, scrypt, Why not MD5 or SHA for passwords, Salts and work factors, HMAC signatures, Symmetric encryption (AES-GCM).

Mini project: Benchmark SHA-256, bcrypt and Argon2id on your machine by hashing 1000 passwords, then implement signup and login using Argon2id with automatic rehashing when parameters change.

Self-check: What does a salt protect against, and what does it not protect against?

Resources:
- [OWASP Password Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html) (OWASP)
- [OWASP Cryptographic Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html) (OWASP)

### HTTPS and TLS

core · beginner · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/tls-https

Encrypt traffic with TLS, obtain certificates automatically and understand what the handshake proves.

**TLS** (Transport Layer Security) encrypts traffic between client and server and proves the server's identity. **HTTPS** is simply HTTP over TLS. Every public backend must use it; browsers mark plain HTTP as insecure and many features require HTTPS.

#### What TLS gives you
- **Confidentiality**: eavesdroppers cannot read the traffic.
- **Integrity**: tampering is detected.
- **Authentication**: the server presents a **certificate** signed by a trusted **Certificate Authority (CA)**, proving it controls the domain.

#### How the handshake works (TLS 1.3, simplified)
The client and server agree on a cipher suite and perform a key exchange (ECDHE) to derive shared session keys. The server sends its certificate chain, which the client validates up to a root CA it trusts. Then encrypted application data flows.

#### In practice
- Get free, automatically renewed certificates from **Let's Encrypt** via certbot, or let Caddy, your PaaS, load balancer or CDN handle it.
- Terminate TLS at a reverse proxy or load balancer, and decide whether internal hops also need encryption (in zero-trust setups they do, often via **mTLS**).
- Redirect HTTP to HTTPS and add **HSTS** so browsers never try plain HTTP again.
- Disable old protocols (SSL, TLS 1.0 and 1.1).

#### Pitfalls
- Expired certificates are a classic outage. Automate renewal and alert on expiry.
- Disabling certificate verification in HTTP clients "to make it work".

You are ready to move on when your deployed app has an A rating on an SSL test tool, auto-renewing certificates and HSTS enabled.

Key concepts: Certificates and certificate authorities, TLS 1.3 handshake, Let's Encrypt and certbot, TLS termination at a proxy, HSTS, Mutual TLS (mTLS).

Mini project: Put your VPS-hosted app behind Nginx or Caddy with a Let's Encrypt certificate, HTTP to HTTPS redirect and HSTS, then scan it with an online SSL testing tool.

Self-check: What exactly does a valid TLS certificate prove to the browser, and what does it not prove?

Resources:
- [Let's Encrypt documentation](https://letsencrypt.org/docs/) (Let's Encrypt)
- [MDN: Transport Layer Security](https://developer.mozilla.org/en-US/docs/Web/Security/Transport_Layer_Security) (MDN)
- [What is TLS?](https://www.cloudflare.com/learning/ssl/transport-layer-security-tls/) (Cloudflare)

### CORS, CSP and Security Headers

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/browser-facing-security

Configure cross-origin access and browser security headers correctly instead of copying permissive snippets.

Browsers enforce the **same-origin policy**: a page from `https://app.example.com` cannot freely read responses from `https://api.other.com`. Backends relax or reinforce this with headers.

#### CORS (Cross-Origin Resource Sharing)
CORS lets your API tell browsers which other origins may call it.
- Simple requests get an `Access-Control-Allow-Origin` check on the response.
- Non-simple requests (custom headers, JSON bodies with PUT/DELETE) trigger a **preflight** `OPTIONS` request first.
- To send cookies cross-origin you need `Access-Control-Allow-Credentials: true` and an explicit origin, never `*`.
- Keep an allowlist of origins. CORS is a browser protection, not an authentication mechanism: curl ignores it entirely.

#### CSP (Content Security Policy)
The `Content-Security-Policy` header tells the browser which sources of scripts, styles, images and frames are allowed. A strict CSP (for example nonce-based scripts) greatly reduces the impact of XSS. Relevant whenever your backend serves HTML.

#### Other headers worth setting
- `Strict-Transport-Security` (HSTS)
- `X-Content-Type-Options: nosniff`
- `Referrer-Policy`
- `frame-ancestors` in CSP (or `X-Frame-Options`) against clickjacking

Middleware such as **helmet** (Node) sets sensible defaults.

#### Pitfalls
- Reflecting any `Origin` header back with credentials allowed. That is effectively disabling the protection.

You are ready to move on when you can explain a preflight request from the network tab and your API allows exactly the origins it should.

Key concepts: Same-origin policy, CORS and preflight requests, Credentials and CORS, Content Security Policy, Clickjacking protection, helmet and header middleware.

Mini project: Serve a frontend from one origin and your API from another, get cookie-based auth working across them with a strict CORS allowlist, then add a CSP and verify a test inline script is blocked.

Self-check: Why does CORS not protect your API from a malicious script running on a server?

Resources:
- [MDN: Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) (MDN)
- [MDN: Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) (MDN)
- [OWASP HTTP Headers Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html) (OWASP)

### Common Vulnerabilities: OWASP Top 10

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/owasp-top-ten

Learn the most common web application risks, how attackers exploit them and the standard defenses.

The **OWASP Top 10** is a regularly updated list of the most critical web application security risks. It is the shared vocabulary of security reviews and interviews.

#### The risks you must be able to explain and prevent
- **Broken access control**: IDOR, missing checks on admin routes. Defense: deny by default, server-side checks, tests.
- **Injection** (SQL, NoSQL, OS command, LDAP): user input interpreted as code. Defense: parameterized queries, avoid shelling out, validate input.
- **Cross-site scripting (XSS)**: attacker script runs in other users' browsers. Defense: output encoding, templating that escapes by default, CSP.
- **Cryptographic failures**: plain HTTP, weak hashing, secrets in code.
- **Security misconfiguration**: default credentials, verbose error pages with stack traces, open cloud buckets.
- **Vulnerable and outdated components**: old dependencies with known CVEs. Defense: `npm audit`, Dependabot or Renovate, and actually merging updates.
- **Identification and authentication failures**: no rate limiting, weak password policies, broken session handling.
- **SSRF** (server-side request forgery): your server fetches a URL the attacker controls, reaching internal services like cloud metadata endpoints. Defense: allowlists, block private IP ranges.
- **Insecure design**, **integrity failures** (unsigned updates, unsafe deserialization) and **logging and monitoring failures**.

#### Habits that prevent most issues
Validate input at boundaries, encode output, use proven libraries, keep dependencies current, apply least privilege and log security-relevant events.

You are ready to move on when you can exploit and then fix SQL injection, XSS and IDOR in a deliberately vulnerable practice app such as OWASP Juice Shop.

Key concepts: Broken access control, Injection attacks, Cross-site scripting (XSS), SSRF, Dependency scanning, Security misconfiguration, Unsafe deserialization, OWASP Juice Shop practice.

Mini project: Run OWASP Juice Shop locally, complete five beginner challenges, then audit your own project against the Top 10 and fix at least two findings.

Self-check: Your service fetches a user-supplied image URL. What could an attacker do with that, and how do you prevent it?

Resources:
- [OWASP Top Ten](https://owasp.org/www-project-top-ten/) (OWASP)
- [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/) (OWASP)
- [OWASP Juice Shop](https://owasp.org/www-project-juice-shop/) (OWASP)

### Managing Secrets and Configuration

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/secrets-management

Keep API keys, database passwords and signing keys out of code and rotate them safely.

A **secret** is anything that grants access: database passwords, API keys, JWT signing keys, OAuth client secrets, cloud credentials. Leaked secrets are one of the most common causes of real breaches, often through a public Git repository.

#### The basics
- Never commit secrets. Keep `.env` in `.gitignore` and commit a `.env.example` with placeholder values.
- Load secrets from **environment variables** or a secrets manager at runtime (twelve-factor style), and validate them at startup so the app fails fast when one is missing.
- Use **different secrets per environment**; development keys should never work in production.

#### Secret managers
Cloud options include **AWS Secrets Manager / Parameter Store**, **GCP Secret Manager** and **Azure Key Vault**; **HashiCorp Vault** and **Doppler** or **Infisical** are popular platform-neutral tools. They offer access control, audit logs, versioning and rotation. In Kubernetes, remember that plain Secrets are only base64-encoded; enable encryption at rest or use an external secrets operator.

#### Rotation and response
- Design for rotation: support two valid keys during a changeover.
- If a secret leaks, **rotate it immediately**; deleting the commit is not enough because it may already be cloned or scraped.
- Enable secret scanning in your repo host and in CI.

#### Least privilege
Give each service its own credentials with only the permissions it needs, so a leak has a small blast radius.

You are ready to move on when your app reads every secret from the environment or a manager, fails clearly on a missing value, and you have practiced rotating a database password without downtime.

Key concepts: Environment variables and .env files, Startup config validation, Cloud secret managers, HashiCorp Vault, Secret rotation, Secret scanning, Least-privilege credentials.

Mini project: Move all secrets in a project into environment variables validated with a schema at startup, enable secret scanning on the repo, and write a rotation procedure for the database password.

Self-check: You accidentally pushed an API key to a public repo and force-pushed to remove it. Is the problem solved? What should you do?

Resources:
- [OWASP Secrets Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html) (OWASP)
- [HashiCorp Vault documentation](https://developer.hashicorp.com/vault/docs) (HashiCorp)
- [The Twelve-Factor App: Config](https://12factor.net/config) (12factor.net)

## Testing and Shipping Continuously

Build confidence in your code with automated tests, then ship it through an automated pipeline.

### Unit Testing Fundamentals

core · beginner · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/unit-testing

Write fast, focused tests for your logic with a test runner, assertions and sensible use of test doubles.

A **unit test** checks a small piece of logic (a function, a class) in isolation, runs in milliseconds and gives precise feedback when something breaks. Unit tests are the base of a healthy test suite.

#### What to learn
- A test runner for your stack: **Vitest** or **Jest** (Node), **pytest** (Python), `go test`, **JUnit 5** (Java), **xUnit** (.NET), **RSpec** (Ruby).
- The **Arrange, Act, Assert** structure and descriptive test names ("returns 0 discount for orders under 50").
- **Test doubles**: stubs return canned data, mocks verify interactions, fakes are lightweight working implementations (like an in-memory repository). Prefer fakes and real objects over heavy mocking.
- **Coverage** as a flashlight for untested code, not a target to game.

#### Design for testability
Keep business logic in pure functions or classes that receive their dependencies (dependency injection) instead of importing a database client directly. Then logic is trivially testable, and I/O is tested separately.

#### Pitfalls
- Testing implementation details, so every refactor breaks tests.
- Mocking everything, which makes tests pass while the real system fails.
- Flaky tests that depend on time, randomness or ordering. Inject clocks and seeds.

You are ready to move on when your project's core business rules are covered by fast unit tests that run on every save and read like a specification.

Key concepts: Test runners (Vitest, Jest, pytest, JUnit), Arrange, Act, Assert, Stubs, mocks and fakes, Dependency injection for testability, Code coverage, Avoiding flaky tests, Property-based testing.

Mini project: Extract the pricing or discount logic from one of your projects into a pure module and cover it with at least 15 unit tests, including edge cases and a fake clock.

Self-check: What is the difference between a stub and a mock, and why can too many mocks make a test suite less trustworthy?

Resources:
- [The Practical Test Pyramid](https://martinfowler.com/articles/practical-test-pyramid.html) (Martin Fowler)
- [Vitest guide](https://vitest.dev/guide/) (Vitest)
- [pytest documentation](https://docs.pytest.org/) (pytest)

### Integration and End-to-End Testing

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/integration-e2e-testing

Test your API against real databases and dependencies, and verify full user flows end to end.

Unit tests prove your logic; **integration tests** prove the pieces work together: your code with a real database, a real HTTP layer, a real queue. **Functional or end-to-end (e2e) tests** exercise complete user flows from the outside, the way a client would.

#### Integration testing an API
- Start your app in-process and send real HTTP requests (Supertest, FastAPI TestClient, Spring MockMvc, WebApplicationFactory).
- Use a **real database engine**, not a mock. **Testcontainers** spins up PostgreSQL, Redis or Kafka in Docker per test run.
- Reset state between tests with transactions that roll back, truncation or a fresh schema.
- Test the unhappy paths: validation errors, auth failures, conflicts.

#### End-to-end tests
Run the deployed system (or a production-like staging) and drive it through user journeys: sign up, create an order, receive an email. For APIs this can be a collection of HTTP scenarios; for full-stack apps, browser tools like **Playwright**. Keep e2e tests few and focused on critical paths because they are slow and more brittle.

#### Contract tests
In multi-service systems, **consumer-driven contract tests** (for example Pact) check that a provider still satisfies what its consumers expect, without deploying everything together.

#### The shape of a good suite
Many unit tests, a solid layer of integration tests, and a thin layer of e2e tests. Many backend teams find integration tests give the best confidence per minute.

You are ready to move on when your API has integration tests against a real Postgres in Docker that run in CI in under a few minutes.

Key concepts: HTTP-level API tests, Testcontainers, Test data and database reset, End-to-end user journeys, Playwright, Contract testing with Pact, Load testing (k6).

Mini project: Write integration tests for your API's signup, login and create-resource endpoints against a Testcontainers PostgreSQL, including tests for 401, 403 and 422 responses.

Self-check: Why can mocking the database in API tests give false confidence?

Resources:
- [Testcontainers](https://testcontainers.com/) (Testcontainers)
- [Playwright documentation](https://playwright.dev/docs/intro) (Microsoft)
- [Pact documentation](https://docs.pact.io/) (Pact)

### Test-Driven Development

optional · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/test-driven-development

Practice the red, green, refactor cycle to drive design with tests.

**Test-Driven Development (TDD)** flips the usual order: write a failing test first, write the minimum code to make it pass, then refactor with the test as a safety net. The cycle is short, often just a few minutes: **red, green, refactor**.

#### Why people practice it
- It forces you to think about the interface and behavior before implementation.
- It produces code that is testable by construction, with small units and clear dependencies.
- Refactoring becomes fearless because every behavior is pinned by a test.

#### How to practice
- Start with **katas** (small exercises such as a bowling score calculator or a string calculator) to build the rhythm.
- Take tiny steps. If a test takes more than a few minutes to make green, the step was too big.
- Refactor both production code and tests; duplication in tests hurts too.

#### Where it fits best
TDD shines for business logic with clear rules (pricing, validation, state machines) and for bug fixes: write a test that reproduces the bug before fixing it. It is less natural for exploratory spikes or UI layout. Many experienced developers use it selectively rather than dogmatically.

You are ready to move on when you have completed a kata in strict TDD and fixed at least one real bug by writing the failing test first.

Key concepts: Red, green, refactor, Coding katas, Test-first bug fixing, Behavior-driven development (BDD).

Mini project: Build a shopping cart module with discounts and tax rules entirely test-first, committing after each green step so the history shows the cycle.

Self-check: Why does TDD tend to produce code with fewer hidden dependencies?

Resources:
- [Test Driven Development](https://martinfowler.com/bliki/TestDrivenDevelopment.html) (Martin Fowler)
- [Learn Go with Tests](https://quii.gitbook.io/learn-go-with-tests) (Chris James)

### Continuous Integration and Delivery

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/ci-cd

Automate builds, tests and deployments so every change to main is verified and shippable.

**Continuous Integration (CI)** means every push and pull request is automatically built and tested, so problems surface within minutes. **Continuous Delivery (CD)** extends this so every change that passes is ready to deploy with one click; **Continuous Deployment** ships it automatically.

#### A typical backend pipeline
1. Install dependencies (with caching).
2. Lint and type-check.
3. Run unit and integration tests (spinning up Postgres or Redis as service containers).
4. Build an artifact, usually a **Docker image**, tagged with the commit SHA.
5. Push the image to a registry.
6. Deploy to staging, run smoke tests, then promote to production.
7. Run database migrations as a controlled step.

#### Tools
**GitHub Actions** is the most common starting point; **GitLab CI**, **CircleCI**, **Jenkins**, **Buildkite** and cloud-native options are all widespread. Concepts transfer: workflows, jobs, steps, runners, secrets and artifacts.

#### Deployment strategies
- **Rolling**: replace instances gradually.
- **Blue-green**: run the new version alongside the old and switch traffic at once.
- **Canary**: send a small percentage of traffic to the new version and watch metrics.
- **Feature flags** decouple deploying code from releasing features.

#### Pitfalls
- Slow pipelines that people learn to ignore. Keep CI under about ten minutes.
- Secrets printed in logs. Use the platform's secret store and masking.
- No rollback plan.

You are ready to move on when a merge to main in your project automatically tests, builds an image and deploys it, and you have rolled back a bad deploy at least once.

Key concepts: GitHub Actions, GitLab CI, Jenkins, CircleCI, Pipeline stages and caching, Service containers for tests, Artifacts and image registries, Rolling, blue-green and canary, Feature flags, Rollbacks.

Mini project: Create a GitHub Actions workflow that runs lint, tests against a Postgres service container, builds and pushes a Docker image, and deploys to your PaaS on merge to main.

Self-check: What is the difference between continuous delivery and continuous deployment, and why might a team choose one over the other?

Resources:
- [GitHub Actions documentation](https://docs.github.com/en/actions) (GitHub)
- [GitLab CI/CD](https://docs.gitlab.com/ci/) (GitLab)
- [Continuous Integration](https://martinfowler.com/articles/continuousIntegration.html) (Martin Fowler)

## Caching for Speed

Serve repeated work from memory or the edge, and keep cached data correct.

### Server-Side Caching with Redis

core · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/server-side-caching

Cache expensive results in Redis or Memcached using the right pattern, TTLs and invalidation strategy.

A cache stores the result of expensive work (a slow query, an external API call, a rendered page) so the next request is served from fast memory. Caching is often the cheapest big performance win, and also a common source of stale-data bugs.

#### Stores
- **Redis**: an in-memory data structure server with strings, hashes, lists, sets, sorted sets, TTLs, pub/sub and streams. The default choice; also used for sessions, rate limiting and queues.
- **Memcached**: a simpler, multi-threaded key-value cache. Fine when you only need plain get/set.
- **In-process caches** (an LRU map in your app): fastest, but each instance has its own copy and memory is limited.

#### Patterns
- **Cache-aside** (most common): read from cache; on a miss, load from the database and populate the cache with a TTL.
- **Write-through**: write to the cache and database together.
- **Write-behind**: write to cache, flush to the database later (risky, rarely needed).

#### Invalidation
"There are only two hard things in computer science: cache invalidation and naming things." Options: short **TTLs**, deleting keys on writes, or versioned keys (`user:42:v7`). Choose based on how stale data may be.

#### Pitfalls
- **Cache stampede**: a hot key expires and thousands of requests hit the database at once. Use locking, request coalescing or jittered TTLs.
- Caching per-user data under a shared key and leaking it to other users.
- Treating the cache as the source of truth. It can be evicted any time.

You are ready to move on when you can add cache-aside caching to a slow endpoint, measure the latency improvement and explain your invalidation rule.

Key concepts: Redis data structures, Memcached, In-process LRU caches, Cache-aside pattern, Write-through and write-behind, TTLs and invalidation, Cache stampede prevention, Eviction policies.

Mini project: Add Redis cache-aside to a slow product listing endpoint, invalidate on product updates, add jittered TTLs, and load-test before and after to report p50 and p95 latency.

Self-check: A popular cache key expires and your database CPU spikes to 100 percent. What happened and how do you prevent it?

Resources:
- [Redis documentation](https://redis.io/docs/) (Redis)
- [Memcached](https://memcached.org/) (Memcached)
- [Caching guidance (Azure Architecture Center)](https://learn.microsoft.com/en-us/azure/architecture/best-practices/caching) (Microsoft Learn)

### HTTP Caching, CDNs and Client Caches

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/http-caching-cdn

Use Cache-Control, ETags and CDNs so browsers and edge servers do the work instead of your origin.

The fastest request is one that never reaches your server. HTTP has a built-in caching model that browsers, proxies and **CDNs** understand; your job is to send the right headers.

#### Cache-Control
- `Cache-Control: public, max-age=31536000, immutable` for fingerprinted static assets (`app.3f9a1c.js`).
- `Cache-Control: private, max-age=60` for per-user responses that only the browser may cache.
- `Cache-Control: no-store` for sensitive data that must never be cached.
- `s-maxage` sets a different lifetime for shared caches like CDNs; `stale-while-revalidate` serves slightly old content while fetching fresh content in the background.

#### Validation
With an **ETag** (a version fingerprint) or `Last-Modified`, clients send `If-None-Match` or `If-Modified-Since` and your server can reply **304 Not Modified** with no body, saving bandwidth.

#### CDNs
A **Content Delivery Network** (Cloudflare, Fastly, CloudFront, Akamai) caches responses at edge locations close to users, absorbing traffic spikes and reducing latency. Beyond static files, CDNs can cache API responses, terminate TLS, block attacks and run edge functions. Plan for **purging** when content changes.

#### Client-side caching
Browsers also cache in memory and on disk, and apps use Service Workers, localStorage or client libraries (React Query, SWR) to cache API data. The backend's headers and ETags make those clients efficient.

#### Pitfalls
- Caching authenticated responses on a shared CDN without varying on the right headers, leaking one user's data to another.
- Forgetting the `Vary` header when responses differ by `Accept-Encoding` or language.

You are ready to move on when your static assets are served from a CDN with long-lived immutable caching and an API endpoint returns ETags that produce 304 responses.

Key concepts: Cache-Control directives, ETag and 304 Not Modified, Vary header, CDNs and edge caching, Cache purging, stale-while-revalidate, Client-side caching.

Mini project: Put a free CDN in front of your app, configure immutable caching for static assets and short shared caching for a public API endpoint, and verify cache hits using response headers.

Self-check: Why is putting 'Cache-Control: public' on a response that includes the logged-in user's name dangerous behind a CDN?

Resources:
- [MDN: HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching) (MDN)
- [What is a CDN?](https://www.cloudflare.com/learning/cdn/what-is-a-cdn/) (Cloudflare)
- [Prevent unnecessary network requests with the HTTP Cache](https://web.dev/articles/http-cache) (web.dev)

## Files, Email and Payments

The everyday product features almost every backend ends up owning: uploads, outbound messages and money.

### File Storage and Uploads with Object Storage

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/file-storage-uploads

Accept, store and serve user files safely using object storage like S3 instead of your server's disk.

Sooner or later users upload avatars, PDFs or videos. Storing them on the app server's local disk breaks as soon as you run two instances or redeploy a container. The standard answer is **object storage**: Amazon S3 and its compatible cousins (Cloudflare R2, Google Cloud Storage, Azure Blob, self-hosted MinIO).

#### The mental model
Object storage is a flat key-value store for blobs. A **bucket** holds **objects**, each addressed by a key such as `users/42/avatar.png`, with metadata like content type. There are no real folders, just key prefixes. It is cheap, durable and scales without you thinking about disks.

#### Upload patterns
- **Proxy upload**: the client sends the file to your API, which streams it to storage. Simple, but your server carries all the bytes.
- **Presigned URL upload** (recommended): your API checks permissions, then returns a short-lived signed URL; the client uploads directly to the bucket. Your server only stores the key in the database.
- For large files use **multipart uploads** so a failed chunk can be retried without restarting.

#### Serving files
Keep buckets private by default. Serve public assets through a CDN, and serve private files with short-lived **presigned download URLs** after an authorization check.

#### Security pitfalls
- Trusting the client's filename or `Content-Type`. Generate your own keys and validate type and size on the server.
- Serving user uploads from your main domain, which can enable stored XSS. Use a separate domain or force `Content-Disposition: attachment`.
- Public buckets created "just for testing" that leak customer data.

You are ready to move on when you can implement presigned uploads with size limits, record the object key in your database and serve the file back only to its owner.

Key concepts: Buckets, objects and keys, Presigned upload and download URLs, Multipart and resumable uploads, Validating type and size, Serving files through a CDN, Image resizing pipelines, Lifecycle rules and storage classes, S3-compatible stores (R2, MinIO).

Mini project: Add profile pictures to an API: issue a presigned upload URL limited to 2 MB images, store the key, generate a thumbnail in a background step and serve it via a presigned download URL.

Self-check: Why is uploading directly from the browser to S3 with a presigned URL usually better than streaming the file through your API?

Resources:
- [Amazon S3 User Guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) (AWS)
- [Working with presigned URLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html) (AWS)
- [OWASP File Upload Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html) (OWASP)
- [Cloudflare R2 documentation](https://developers.cloudflare.com/r2/) (Cloudflare)

### Transactional Email and Notifications

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/email-notifications

Send password resets, receipts and alerts reliably through email providers, push and in-app channels.

Signup confirmations, password resets, receipts and alerts are all backend responsibilities. They look trivial ("just send an email") but reliability and deliverability take real care.

#### Use a provider, not your own mail server
Services such as Amazon SES, Postmark, Resend, SendGrid or Mailgun expose an HTTP API or SMTP relay. They handle IP reputation, bounces and complaints. Running your own SMTP server for product email is almost never worth it.

#### Deliverability basics
Inbox providers decide whether your mail is spam largely from DNS records on your sending domain:
- **SPF** lists which servers may send for your domain.
- **DKIM** cryptographically signs each message.
- **DMARC** tells receivers what to do when SPF or DKIM fail and where to send reports.
Separate **transactional** mail (resets, receipts) from **marketing** mail, ideally on different subdomains, so a newsletter complaint does not hurt your password resets.

#### Send asynchronously
Never call the email API inside the request that the user is waiting on. Enqueue a job and let a worker send it with retries. Store a record of what was sent so support can answer "did the reset email go out?".

#### Other channels
- **Web and mobile push** (Web Push, FCM, APNs) for timely alerts.
- **In-app notifications** stored in your database with a read flag.
- **SMS** via providers like Twilio, used sparingly because it costs money per message.
A small **notification service** that picks channels based on user preferences keeps this logic out of your business code.

#### Pitfalls
- Password reset links that never expire or can be reused.
- Sending to users who unsubscribed, which is both bad practice and often illegal.

You are ready to move on when your app sends templated emails from a queue, your domain passes SPF, DKIM and DMARC checks, and users can control which notifications they receive.

Key concepts: Email provider APIs and SMTP, SPF, DKIM and DMARC, Templating emails, Sending from a background queue, Bounces and complaints, Push notifications (FCM, APNs, Web Push), In-app notification feeds, User notification preferences.

Mini project: Build a password reset flow that enqueues a templated email, uses a single-use token that expires in 30 minutes, and logs each send with its provider message id.

Self-check: Your reset emails are landing in spam. Which three DNS records do you check first, and what does each one prove?

Resources:
- [What is a DMARC record?](https://www.cloudflare.com/learning/dns/dns-records/dns-dmarc-record/) (Cloudflare)
- [Amazon SES Developer Guide](https://docs.aws.amazon.com/ses/latest/dg/Welcome.html) (AWS)
- [MDN: Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API) (MDN)

### Payments, Webhooks and Idempotency

recommended · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/payments-webhooks

Integrate a payment provider safely and handle incoming webhooks exactly once, even when they arrive twice.

Money is where backend bugs become very expensive. You should almost never touch raw card numbers: providers like **Stripe**, Adyen, PayPal or Razorpay host the card form, and your backend works with their objects (customers, payment intents, subscriptions).

#### The typical flow
1. Your API creates a payment or checkout session with the provider for a specific order and amount (computed on the server, never trusted from the client).
2. The customer pays on the provider's hosted page or embedded component.
3. The provider notifies you through a **webhook**: an HTTP POST to your endpoint saying the payment succeeded, failed or was refunded.
4. Your webhook handler marks the order paid and triggers fulfilment.

#### Webhooks done right
- **Verify the signature** on every webhook using the shared secret; otherwise anyone can POST "payment succeeded".
- **Respond fast** (2xx within a few seconds) and do heavy work in a background job.
- **Expect duplicates and reordering.** Providers retry on failure, so store the event id and skip events you already processed. Fetch the latest object state instead of trusting event order.

#### Idempotency for outgoing calls
Network calls can time out after the charge actually happened. Send an **idempotency key** (for example the order id) with create requests so a retry does not charge twice. Design your own POST endpoints the same way for clients that retry.

#### Money in code
Store amounts as integers in the smallest unit (cents, paise) plus a currency code; never use floating point. Keep an append-only ledger of payment events for audits and reconciliation.

You are ready to move on when you can take a test-mode payment end to end, replay the same webhook twice without double fulfilment, and explain why the client must not send the price.

Key concepts: Hosted checkout and payment intents, Webhook signature verification, Handling duplicate and out-of-order events, Idempotency keys, Storing money as integers, Subscriptions and billing cycles, Refunds, disputes and reconciliation, PCI DSS scope basics.

Mini project: Integrate a payment provider in test mode for a small shop: server-side order totals, a signed webhook handler that records processed event ids, and a script that replays webhooks to prove idempotency.

Self-check: Your server times out while creating a charge and the client retries. How do you guarantee the customer is charged only once?

Resources:
- [Stripe: Receive events with webhooks](https://docs.stripe.com/webhooks) (Stripe)
- [Stripe: Idempotent requests](https://docs.stripe.com/api/idempotent_requests) (Stripe)
- [Standard Webhooks specification](https://www.standardwebhooks.com/) (Standard Webhooks)

## Beyond Relational: NoSQL and Search

Know the non-relational data stores, what access patterns they are built for, and when a search engine beats SQL.

### NoSQL Families and When to Use Them

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/nosql-fundamentals

Understand document, key-value, wide-column, graph and time-series stores and the trade-offs they make versus SQL.

"NoSQL" is not one technology but a family of databases that relax parts of the relational model to win at specific workloads. Knowing the families helps you pick deliberately instead of following hype.

#### The main families
- **Document stores** (MongoDB, Couchbase, Firestore): JSON-like documents with flexible fields. Good for aggregates you read and write as a whole, like a product with its variants.
- **Key-value stores** (Redis, DynamoDB, etcd): look up a value by key, extremely fast and simple. Good for sessions, caches, counters and well-known access patterns.
- **Wide-column stores** (Cassandra, ScyllaDB, HBase): rows partitioned across many nodes, tuned for huge write volumes.
- **Graph databases** (Neo4j, Amazon Neptune): nodes and relationships as first-class data, good for traversals like "friends of friends".
- **Time-series databases** (InfluxDB, TimescaleDB, Prometheus): append-heavy timestamped measurements with rollups and retention.

#### The trade-offs
Most NoSQL systems give up some combination of joins, flexible ad hoc queries, multi-record transactions or strong consistency in exchange for horizontal scale, schema flexibility or raw speed. **Schema-less rarely means no schema**; it means the schema lives in your application code, so you still need validation and migrations.

#### Design from access patterns
With SQL you normalize first and write queries later. With most NoSQL stores you list the queries first and shape the data to answer them, often duplicating data on purpose.

#### A sane default
Start with a relational database like PostgreSQL (which also has solid JSON support) and add a specialized store when a concrete workload demands it. Many production systems use several: Postgres as the source of truth, Redis for caching, a search engine for text search.

You are ready to move on when you can take three example workloads and justify which family fits each and what you give up.

Key concepts: Document stores, Key-value stores, Wide-column stores, Graph databases, Time-series databases, Access-pattern-first modeling, Polyglot persistence.

Mini project: Write a one-page decision record for a fictional app (chat, analytics dashboard, product catalog) choosing a data store for each feature and listing the trade-offs.

Self-check: What does a document database give up compared to PostgreSQL, and what does it gain in return?

Resources:
- [NoSQL Guide](https://martinfowler.com/nosql.html) (Martin Fowler)
- [What is NoSQL?](https://aws.amazon.com/nosql/) (AWS)
- [Designing Data-Intensive Applications](https://dataintensive.net/) (Martin Kleppmann)

### Document Databases with MongoDB

recommended · intermediate · about 10 h · https://www.internhack.in/roadmaps/tracks/backend/mongodb

Model, query, index and validate data in MongoDB, the most widely used document database.

**MongoDB** stores data as BSON documents (binary JSON) grouped into **collections**. It is the NoSQL database you are most likely to meet in job descriptions and startups, and many Node.js stacks pair it with the Mongoose ODM.

#### Modeling: embed or reference
The central design question is whether related data lives **inside** a document or in a separate collection:
- **Embed** when data is owned by the parent and read together (an order and its line items).
- **Reference** when data is shared, large or grows without bound (users and their thousands of comments).
Documents have a 16 MB limit, and unbounded arrays are a classic performance trap.

#### Querying
- CRUD with `find`, `insertOne`, `updateOne` and operators like `$set`, `$push`, `$in`, `$gte`.
- The **aggregation pipeline** (`$match`, `$group`, `$lookup`, `$project`) handles reporting and joins-when-needed.
- **Indexes** work much like SQL: single-field, compound (order matters), multikey for arrays, text and TTL indexes. Use `explain()` to confirm queries hit an index.

#### Consistency and safety
Single-document writes are atomic, and multi-document **transactions** exist on replica sets, but a design that needs them everywhere is a hint you wanted a relational database. Use **schema validation** (JSON Schema rules on the collection) or an ODM so bad data does not creep in.

#### Pitfalls
- Treating "no schema" as "no design", ending with ten shapes of the same entity.
- Missing indexes, which turn every query into a collection scan.
- Exposing the database to the internet without authentication, historically a major source of breaches.

You are ready to move on when you can model a blog with posts, comments and tags, justify each embed or reference decision, and show via `explain()` that your main queries use indexes.

Key concepts: Documents, collections and BSON, CRUD operations and query operators, Embedding vs referencing, Indexes and explain(), Aggregation pipeline, Schema validation, Mongoose ODM, Multi-document transactions.

Mini project: Build a small blog API on MongoDB with embedded comments, referenced authors, a compound index for the feed query and an aggregation that returns post counts per tag.

Self-check: When would you move comments out of the post document into their own collection?

Resources:
- [MongoDB Manual](https://www.mongodb.com/docs/manual/) (MongoDB)
- [MongoDB data modeling](https://www.mongodb.com/docs/manual/data-modeling/) (MongoDB)
- [MongoDB University](https://learn.mongodb.com/) (MongoDB)

### Key-Value Stores and DynamoDB

optional · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/key-value-dynamodb

Use key-value data stores like Redis as a primary store and DynamoDB for serverless-scale workloads.

Key-value databases trade query flexibility for predictable speed: you fetch or write by key, and the system can spread keys across many machines.

#### Redis beyond caching
You met Redis as a cache. It also works as a primary store for data with simple access patterns, using its data structures directly:
- **Hashes** for objects, **sorted sets** for leaderboards and time-ordered feeds, **sets** for membership, **streams** for event logs.
- Atomic commands like `INCR` and Lua scripts for counters and rate limiters.
Understand its persistence options (**RDB** snapshots, **AOF** logs) before trusting it with data you cannot lose.

#### DynamoDB
Amazon's managed key-value and document database scales to huge throughput with no servers to run. Its model is strict:
- Every item has a **partition key** (and optionally a **sort key**). Queries must specify the partition key; scanning the whole table is slow and expensive.
- **Global secondary indexes** give you additional access patterns.
- **Single-table design** stores several entity types in one table with carefully designed keys like `PK = USER#42`, `SK = ORDER#2024-05-01`.
- Capacity is **on-demand** or **provisioned**, and hot partitions throttle.

#### When they fit
Session stores, shopping carts, feature flags, user profiles fetched by id, IoT device state and serverless apps where you want zero database administration.

#### Pitfalls
- Choosing DynamoDB before knowing your queries, then needing ad hoc filtering it cannot do efficiently.
- Low-cardinality partition keys (like `status`) that create hot partitions.

You are ready to move on when you can design a DynamoDB key schema for users and their orders that answers "orders for user X, newest first" without a scan.

Key concepts: Redis data structures as primary data, Redis persistence: RDB and AOF, Partition and sort keys, Global secondary indexes, Single-table design, Hot partitions and capacity modes.

Mini project: Build a leaderboard with Redis sorted sets and an order history table in DynamoDB Local with a key design that supports two different query patterns.

Self-check: Why does DynamoDB punish you for not knowing your access patterns up front?

Resources:
- [Amazon DynamoDB Developer Guide](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) (AWS)
- [DynamoDB best practices](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html) (AWS)
- [Redis data types](https://redis.io/docs/latest/develop/data-types/) (Redis)

### Wide-Column Stores: Cassandra and ScyllaDB

optional · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/cassandra-wide-column

Understand how Cassandra-style databases handle massive write volumes across many nodes and data centers.

**Apache Cassandra** and its C++ reimplementation **ScyllaDB** are built for workloads that write enormous amounts of data and must stay available even when nodes or whole data centers fail: messaging history, IoT telemetry, activity feeds.

#### How it works
- Data is split into **partitions** by a partition key and spread around a ring of nodes using consistent hashing. Each partition is replicated to several nodes (the **replication factor**).
- There is no primary node: any node can accept writes, which makes it very available.
- Writes go to a commit log and memtable and are flushed to immutable SSTables that get **compacted** later, so writes are cheap.

#### Modeling with CQL
CQL looks like SQL but the rules differ. You design **one table per query**:
- The partition key decides which node holds the data; the **clustering columns** decide sort order inside a partition.
- No joins and very limited filtering. Duplicating data across tables is normal.
- Keep partitions bounded (for example bucket messages by conversation and month).

#### Tunable consistency
Each query picks a consistency level such as `ONE`, `QUORUM` or `ALL`. With replication factor 3, writing and reading at QUORUM gives you read-your-writes; using ONE is faster but may return stale data.

#### When not to use it
Small datasets, ad hoc analytics, workloads needing transactions across rows, or teams without the operational capacity to run a distributed database. Managed services (Astra, ScyllaDB Cloud, Amazon Keyspaces) lower that cost.

You are ready to move on when you can design a table for "latest 50 messages in a conversation" and explain what QUORUM means with replication factor 3.

Key concepts: Partitions and consistent hashing, Replication factor, Partition keys and clustering columns, Query-first table design, Tunable consistency levels, Compaction and tombstones.

Mini project: Run Cassandra or ScyllaDB in Docker and model a chat app's message history with time-bucketed partitions, then query the latest messages per conversation.

Self-check: Why is deleting lots of rows in Cassandra potentially bad for read performance?

Resources:
- [Apache Cassandra documentation](https://cassandra.apache.org/doc/latest/) (Apache)
- [ScyllaDB University](https://university.scylladb.com/) (ScyllaDB)

### Graph Databases with Neo4j

optional · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/graph-databases

Model highly connected data as nodes and relationships and query deep traversals with Cypher.

Some data is mostly about **connections**: social networks, recommendation engines, fraud rings, access-control hierarchies, knowledge graphs. In SQL, "friends of friends of friends" becomes a pile of self-joins that slow down with each hop. A **graph database** stores relationships directly, so traversals stay fast.

#### The property graph model
- **Nodes** represent entities and carry labels (`:Person`, `:Product`) and properties.
- **Relationships** connect nodes, have a type (`:FOLLOWS`, `:BOUGHT`) and a direction, and can carry properties too.

#### Cypher queries
Neo4j's query language uses ASCII-art patterns:
`MATCH (me:Person {id: 1})-[:FOLLOWS]->()-[:FOLLOWS]->(suggestion) WHERE NOT (me)-[:FOLLOWS]->(suggestion) RETURN suggestion LIMIT 10`
That reads as "people followed by the people I follow, whom I do not follow yet". Cypher ideas are now standardized as **GQL**.

#### When to reach for it
- Queries with variable or deep path lengths (shortest path, recommendations).
- Relationship-heavy domains where the relationships themselves are the product.
For simple hierarchies, PostgreSQL recursive CTEs are often enough, so try those first.

#### Pitfalls
- Using a graph database as a general-purpose store for tabular data.
- "Supernodes" with millions of relationships (a celebrity account) that make traversals slow unless modeled carefully.

You are ready to move on when you can model a small social graph and write a Cypher query for mutual connections and one for shortest path.

Key concepts: Nodes, relationships and properties, Cypher pattern matching, Traversals and shortest path, Recursive CTEs as an SQL alternative, Supernodes.

Mini project: Load a small follow graph into Neo4j and build an endpoint that returns 'people you may know' ranked by mutual connections.

Self-check: Why does a friends-of-friends-of-friends query get slower in SQL but stay manageable in a graph database?

Resources:
- [Neo4j documentation](https://neo4j.com/docs/) (Neo4j)
- [Neo4j GraphAcademy](https://graphacademy.neo4j.com/) (Neo4j)

### Time-Series Databases

optional · advanced · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/time-series-databases

Store and query timestamped measurements efficiently with TimescaleDB or InfluxDB.

Metrics, sensor readings, stock ticks and application events share a shape: an ever-growing stream of **timestamped values** that are written once, rarely updated, and queried by time range with aggregation ("average CPU per 5 minutes over the last day").

#### Why a specialized store
A plain table works at first, but at millions of rows per day you want:
- **Time-based partitioning** (chunks per day or hour) so queries only touch relevant data.
- **Compression** tuned for sequential numbers, often 10x or more.
- **Retention policies** that drop old raw data automatically.
- **Downsampling** or continuous aggregates that keep hourly rollups after raw data expires.

#### Common options
- **TimescaleDB**: a PostgreSQL extension. You keep SQL, joins and your existing tooling, and gain hypertables, compression and continuous aggregates. The easiest step for teams already on Postgres.
- **InfluxDB**: a purpose-built time-series database with its own ingestion protocol, popular for IoT and monitoring.
- **Prometheus**: specialized for application metrics scraping, covered in observability.
- **ClickHouse**: a columnar analytics database often used for large event and log analytics.

#### Modeling tips
Separate **tags/labels** (low-cardinality dimensions like region or device type) from **fields** (the measured numbers). High-cardinality labels such as user ids can explode index size in some engines.

You are ready to move on when you can ingest a simulated sensor stream, query 5-minute averages over a day, and configure a retention policy.

Key concepts: Time-based partitioning, Retention and downsampling, TimescaleDB hypertables, InfluxDB, Tags vs fields and cardinality, Columnar analytics (ClickHouse).

Mini project: Build a small IoT ingest API that writes readings into TimescaleDB, exposes a time-bucketed chart endpoint and drops raw data older than 7 days.

Self-check: Why is using a user id as a tag a potential problem in a time-series database?

Resources:
- [Timescale documentation](https://docs.timescale.com/) (Timescale)
- [InfluxData documentation](https://docs.influxdata.com/) (InfluxData)

### Full-Text Search Fundamentals

recommended · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/full-text-search-basics

Learn how search engines tokenize, index and rank text, and how far PostgreSQL search can take you.

`WHERE title LIKE '%phone%'` cannot use a normal index, does not match "phones", and has no idea which result is most relevant. **Full-text search** solves this with a different data structure and a ranking model.

#### How search works
- **Analysis**: text is split into **tokens**, lowercased, stripped of stop words and reduced to a root form (**stemming**: "running" becomes "run").
- **Inverted index**: a map from each term to the documents containing it, so lookups are fast regardless of table size.
- **Relevance scoring**: algorithms like **BM25** rank documents higher when the term is rare across the corpus but frequent in the document.
- Extras users expect: typo tolerance (fuzzy matching), prefix search for autocomplete, highlighting, facets and filters.

#### Start with your database
PostgreSQL's built-in search (`tsvector`, `tsquery`, GIN indexes, `ts_rank`) plus the `pg_trgm` extension for fuzzy matching handles product catalogs and docs sites with hundreds of thousands of rows well. MySQL has FULLTEXT indexes too. Keeping search in the database avoids a second system to sync.

#### When to add a search engine
Move to a dedicated engine when you need advanced relevance tuning, multi-language analysis, heavy faceting, very large corpora or search load that should not hit your primary database. Lightweight options like **Meilisearch** or **Typesense** are quick to adopt; **Elasticsearch/OpenSearch** cover the heavy end.

#### Keeping search in sync
The search index is a **derived copy** of your data. Update it from application events or a change-data-capture pipeline, and be able to rebuild it from scratch.

You are ready to move on when you can add ranked, stemmed search with a GIN index to a Postgres table and explain why it beats `LIKE`.

Key concepts: Tokenization and stemming, Inverted indexes, Relevance scoring and BM25, PostgreSQL tsvector and GIN, Fuzzy search with pg_trgm, Meilisearch and Typesense, Keeping the index in sync.

Mini project: Add a search endpoint to a product catalog using Postgres full-text search with ranking, typo tolerance via pg_trgm and highlighted snippets.

Self-check: What is an inverted index, and why can it answer a text query faster than scanning every row?

Resources:
- [PostgreSQL: Full Text Search](https://www.postgresql.org/docs/current/textsearch.html) (PostgreSQL)
- [PostgreSQL: pg_trgm](https://www.postgresql.org/docs/current/pgtrgm.html) (PostgreSQL)
- [Meilisearch documentation](https://www.meilisearch.com/docs) (Meilisearch)

### Search Engines: Elasticsearch and OpenSearch

optional · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/elasticsearch-opensearch

Run a dedicated search cluster for relevance-tuned search, facets and log analytics.

**Elasticsearch** and its open-source fork **OpenSearch** are distributed search and analytics engines built on Apache Lucene. They power site search, e-commerce catalogs, and log analytics stacks. **Apache Solr**, also built on Lucene, is the older sibling still common in enterprise search.

#### Core concepts
- An **index** holds JSON **documents**; it is split into **shards** spread across nodes, each with **replicas** for availability.
- A **mapping** defines field types. `text` fields are analyzed for search, `keyword` fields are exact values for filters, sorting and aggregations. Getting mappings right up front matters because changing them usually means reindexing.
- **Analyzers** control tokenization, stemming, synonyms and language handling.

#### Querying
The Query DSL combines **full-text queries** (`match`, `multi_match`) with **filters** (`term`, `range`) inside a `bool` query. Filters do not affect scoring and are cached. **Aggregations** power facets ("Brand: Apple (42)") and analytics.

#### Operating it
- It is not a primary database. Keep the source of truth elsewhere and feed the index through a sync job, queue or change-data-capture.
- Use **aliases** so you can build a new index and switch traffic to it with zero downtime.
- Watch heap usage, shard count (too many small shards is a common mistake) and cluster health.
Managed offerings (Elastic Cloud, Amazon OpenSearch Service) remove much of the ops burden.

#### Pitfalls
- Relying on dynamic mapping, which guesses types and can break later.
- Deep pagination with `from` and `size`; use `search_after` instead.

You are ready to move on when you can index a product catalog with explicit mappings, return faceted results with filters, and reindex behind an alias without downtime.

Key concepts: Indexes, shards and replicas, Mappings: text vs keyword, Analyzers and synonyms, Bool queries and filters, Aggregations and facets, Index aliases and reindexing, Apache Solr.

Mini project: Sync a product table into OpenSearch, build a search API with facets for brand and price range, and perform a zero-downtime reindex using an alias.

Self-check: Why should a product brand be mapped as keyword rather than text if you want to show it as a facet?

Resources:
- [Elasticsearch reference](https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html) (Elastic)
- [OpenSearch documentation](https://opensearch.org/docs/latest/) (OpenSearch)
- [Apache Solr Reference Guide](https://solr.apache.org/guide/) (Apache)

## Scaling Your Database

Keep the database healthy as traffic grows: pooling, replicas, partitioning and the consistency trade-offs that come with them.

### Connection Pooling

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/connection-pooling

Reuse a bounded set of database connections so your app stays fast and the database does not drown in connections.

Opening a database connection is expensive: TCP handshake, TLS, authentication and, in PostgreSQL, a whole backend process per connection. Doing it per request adds latency, and letting every app instance open hundreds of connections can exhaust the database.

#### Application-side pools
Nearly every driver and ORM has a pool (`pg.Pool`, Prisma's pool, SQLAlchemy's engine pool, HikariCP in Java). The pool keeps a few open connections, lends one to each query or transaction and takes it back afterwards. Key settings:
- **Max size**: total connections this process may hold. The whole fleet's total must stay below the database's limit.
- **Idle timeout** and **max lifetime** so stale connections get recycled.
- **Acquire timeout** so requests fail fast instead of hanging when the pool is exhausted.

#### External poolers
When you run many instances or serverless functions, each with its own pool, use a proxy pooler such as **PgBouncer**, RDS Proxy or Supavisor. In **transaction pooling** mode it multiplexes thousands of client connections onto a few dozen real ones, with caveats: session-level features like some prepared statements or `SET` commands may behave differently.

#### Sizing intuition
More connections is not faster. A database with 8 cores often performs best with a few dozen active connections; beyond that they fight over CPU and locks. Measure instead of guessing.

#### Pitfalls
- Leaking connections by not releasing them on errors, until the pool is empty.
- Holding a connection while calling a slow external API inside a transaction.
- Serverless functions each opening fresh connections and overwhelming the database.

You are ready to move on when you can compute a safe pool size for your fleet, observe pool wait time under load, and explain transaction pooling.

Key concepts: Why connections are expensive, Pool size and timeouts, Connection leaks, PgBouncer and proxy poolers, Session vs transaction pooling, Serverless connection limits.

Mini project: Load test an API with pool size 5, 20 and 100, graph latency and database CPU for each, and put PgBouncer in front to compare.

Self-check: You have 20 app instances each with a pool of 20 and Postgres allows 200 connections. What goes wrong and how do you fix it?

Resources:
- [PgBouncer](https://www.pgbouncer.org/) (PgBouncer)
- [HikariCP: About pool sizing](https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing) (HikariCP)
- [node-postgres: Pooling](https://node-postgres.com/features/pooling) (node-postgres)

### Replication, Read Replicas and Failover

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/replication-read-replicas

Copy data to other database servers for read scaling, high availability and disaster recovery.

**Replication** keeps copies of your database on other servers. It is usually the first scaling and reliability step after tuning queries and adding caching.

#### Primary and replicas
In the common **single-leader** setup, one **primary** accepts writes and streams its changes (in Postgres, the write-ahead log) to one or more **replicas**, which serve reads. Uses:
- **Read scaling**: send heavy read queries and reports to replicas.
- **High availability**: if the primary dies, promote a replica (**failover**).
- **Backups and analytics** from a replica without loading the primary.

#### Synchronous vs asynchronous
- **Asynchronous** replication is fast, but replicas lag behind, and a failover can lose the last few transactions.
- **Synchronous** replication waits for a replica to confirm each commit: no data loss, but higher write latency and risk of stalls if the replica is slow.

#### Replication lag in your code
Reads from a replica can be stale. A user who updates their profile and is redirected to a page served by a lagging replica sees the old data. Common fixes: read-your-writes by routing a user's reads to the primary for a short time after they write, or reading critical paths from the primary always.

#### Other topologies
**Multi-leader** and **leaderless** replication (Cassandra, DynamoDB) accept writes in several places but must resolve conflicts. Managed databases (RDS, Cloud SQL, Neon, Aurora) handle replicas and automatic failover for you, which is the right default for most teams.

#### Replication is not a backup
A bad `DELETE` replicates instantly. You still need point-in-time recovery backups that you have actually tested restoring.

You are ready to move on when you can set up a primary and replica, route reads correctly and describe what happens to in-flight writes during failover.

Key concepts: Primary and read replicas, Synchronous vs asynchronous, Replication lag and read-your-writes, Failover and promotion, Backups and point-in-time recovery, Multi-leader and leaderless replication.

Mini project: Run a Postgres primary and streaming replica with Docker Compose, route read-only endpoints to the replica, and demonstrate lag by pausing replay.

Self-check: Why can a user not see a comment they just posted, and how do you fix it without sending all reads to the primary?

Resources:
- [PostgreSQL: High Availability, Load Balancing, and Replication](https://www.postgresql.org/docs/current/high-availability.html) (PostgreSQL)
- [MySQL: Replication](https://dev.mysql.com/doc/refman/8.0/en/replication.html) (MySQL)
- [Designing Data-Intensive Applications](https://dataintensive.net/) (Martin Kleppmann)

### Partitioning and Sharding

recommended · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/sharding-partitioning

Split big tables and datasets by key so no single table or server has to hold everything.

When one table holds billions of rows, or one server cannot handle the write load, you split the data.

#### Partitioning within one database
**Table partitioning** divides a large table into smaller physical pieces by a key, while queries still see one table. PostgreSQL supports **range** (by month), **list** (by region) and **hash** partitioning. Benefits: queries that filter by the key touch fewer partitions, and dropping an old month is instant instead of a giant `DELETE`. This is often enough and much simpler than sharding.

#### Sharding across servers
**Sharding** puts different subsets of rows on different database servers. Each shard is a full database holding, say, a range of tenant ids.
- **Shard key choice** is everything. A good key spreads load evenly and keeps data queried together on the same shard (tenant id for a B2B SaaS, user id for a social app).
- **Hash-based** sharding spreads evenly; **range-based** keeps ranges together but risks hot spots; a **lookup directory** gives flexibility at the cost of another component.

#### What sharding costs you
- Cross-shard joins and transactions become hard or impossible.
- Resharding when a shard gets too big is a major project.
- Every query must know which shard to hit.
Tools like **Vitess** (MySQL) and **Citus** (Postgres) hide much of this, and distributed SQL databases (CockroachDB, YugabyteDB, Spanner) shard automatically.

#### Before you shard
Exhaust the cheaper options first: better queries and indexes, caching, read replicas, a bigger machine, table partitioning and archiving cold data.

You are ready to move on when you can partition a large events table by month and argue for a shard key in a multi-tenant app.

Key concepts: Range, list and hash partitioning, Choosing a shard key, Hot spots and skew, Cross-shard queries, Resharding, Vitess, Citus and distributed SQL.

Mini project: Convert an events table to monthly range partitions in Postgres, measure query plans before and after, and write a script that detaches partitions older than a year.

Self-check: Why is created_at usually a poor shard key for a write-heavy table?

Resources:
- [PostgreSQL: Table Partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) (PostgreSQL)
- [Vitess documentation](https://vitess.io/docs/) (Vitess)
- [Citus documentation](https://docs.citusdata.com/) (Citus Data)

### CAP, PACELC and Consistency Models

core · advanced · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/cap-consistency-models

Reason about the trade-offs between consistency, availability and latency in distributed data systems.

Once data lives on more than one machine, you must decide what happens when machines disagree or cannot talk to each other.

#### CAP in plain words
The **CAP theorem** says that during a **network partition** a distributed system must choose between **consistency** (every read sees the latest write) and **availability** (every request gets a non-error answer). Since partitions will happen, the real question is what your system does when they do: refuse some requests, or answer with possibly stale data.

#### PACELC
**PACELC** extends CAP: if there is a Partition choose A or C, **Else** (normal operation) choose between **Latency** and **Consistency**. This is the trade-off you feel every day: synchronous replication is consistent but slower; asynchronous is fast but can serve stale reads.

#### Consistency models, strongest to weakest
- **Linearizable (strong)**: behaves like a single copy; after a write completes, everyone sees it.
- **Sequential / causal**: operations appear in an order that respects cause and effect.
- **Read-your-writes, monotonic reads**: per-session guarantees that avoid the most confusing user experiences.
- **Eventual consistency**: replicas converge if writes stop, but reads may be stale for a while.

#### Applying it
- Bank balances, inventory reservations and unique usernames usually need strong consistency.
- Like counts, view counts and feeds are fine with eventual consistency.
Pick per feature, not per company. Also note that "ACID consistency" (constraints hold) and "CAP consistency" (linearizability) are different ideas that share a word.

You are ready to move on when you can classify features of a real app by the consistency they need and explain what a user would see if you chose wrong.

Key concepts: CAP theorem, Network partitions, PACELC, Strong vs eventual consistency, Session guarantees, Quorums, Consensus (Raft, Paxos).

Mini project: Write a short design note for a ticket-booking app deciding which operations need strong consistency and which can be eventual, with the failure scenario for each.

Self-check: Why is 'we picked CA' not a meaningful choice for a system that runs across multiple data centers?

Resources:
- [Consistency Models](https://jepsen.io/consistency) (Jepsen)
- [Please stop calling databases CP or AP](https://martin.kleppmann.com/2015/05/11/please-stop-calling-databases-cp-or-ap.html) (Martin Kleppmann)
- [The Raft Consensus Algorithm](https://raft.github.io/) (raft.github.io)

## Containers, Orchestration and Web Servers

Package your service reproducibly, run it on a cluster and put a battle-tested server in front of it.

### Containers with Docker

core · intermediate · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/docker

Package your app and its dependencies into images that run the same on your laptop, CI and production.

"Works on my machine" disappears when the machine ships with the code. A **container** bundles your app, runtime and system libraries into an isolated process that starts in milliseconds, and **Docker** is the standard toolchain for building and running them.

#### Core concepts
- An **image** is a read-only template built from a **Dockerfile**; a **container** is a running instance of it.
- Images are made of cached **layers**; order Dockerfile steps from least to most frequently changing (install dependencies before copying source) for fast rebuilds.
- **Registries** (Docker Hub, GitHub Container Registry, ECR) store and distribute images.
- **Volumes** persist data outside the container's disposable filesystem; **networks** let containers reach each other by name.

#### A production-quality Dockerfile
- Start from a small, pinned base image (`node:22-slim`, `python:3.12-slim`, distroless).
- Use **multi-stage builds**: compile in one stage, copy only the output into a slim runtime stage.
- Run as a **non-root user**, add a `.dockerignore`, and never bake secrets into the image.
- Read configuration from environment variables so the same image runs everywhere.

#### Docker Compose
`compose.yaml` describes a local stack (API, Postgres, Redis) that starts with `docker compose up`. It is the easiest way to give every developer the same environment.

#### Pitfalls
- Using `latest` tags, which makes deploys unreproducible.
- Huge images full of build tools, slowing every deploy and widening the attack surface.
- Storing database data inside a container without a volume and losing it on restart.

You are ready to move on when your service builds into a small multi-stage image that runs as non-root, and a Compose file brings up the full stack with one command.

Key concepts: Images vs containers, Writing a Dockerfile, Layer caching, Multi-stage builds, Volumes and networks, Docker Compose, Registries and image tags, Image security scanning.

Mini project: Containerize your API with a multi-stage Dockerfile under 200 MB, write a Compose file with Postgres and Redis, and push the image to GitHub Container Registry from CI.

Self-check: Why should you copy the dependency manifest and install packages before copying the rest of your source code?

Resources:
- [Docker: Get started](https://docs.docker.com/get-started/) (Docker)
- [Docker build best practices](https://docs.docker.com/build/building/best-practices/) (Docker)
- [Docker Compose](https://docs.docker.com/compose/) (Docker)

### Kubernetes Basics for Backend Developers

recommended · advanced · about 10 h · https://www.internhack.in/roadmaps/tracks/backend/kubernetes-basics

Understand pods, deployments, services and config well enough to ship and debug your service on a cluster.

**Kubernetes** (K8s) runs containers across a cluster of machines, restarting them when they crash, scaling them and routing traffic to them. As a backend developer you usually do not run the cluster, but you do need to deploy to it and debug your service there.

#### The objects you will touch
- **Pod**: one or more containers scheduled together; the smallest unit. Pods are disposable.
- **Deployment**: declares how many replicas of a pod should run and rolls out new versions gradually.
- **Service**: a stable internal address and load balancer in front of a set of pods.
- **Ingress / Gateway**: routes external HTTP traffic to services.
- **ConfigMap** and **Secret**: configuration and credentials injected as environment variables or files.
- **HorizontalPodAutoscaler**: adds or removes replicas based on CPU or custom metrics.

#### Making your app cluster-friendly
- Expose **liveness** (am I stuck?) and **readiness** (can I take traffic?) probes; they are different questions.
- Set **resource requests and limits** so the scheduler can place pods and one service cannot starve others.
- Handle **SIGTERM** gracefully: stop accepting new work, finish in-flight requests, then exit.
- Keep pods stateless; state lives in databases and object storage.

#### Daily commands
`kubectl get pods`, `kubectl logs`, `kubectl describe pod` (look at Events), `kubectl rollout status` and `kubectl rollout undo` cover most debugging.

#### Is it worth it?
For a small team, a PaaS or managed container service (Cloud Run, ECS, Fly.io, Render) is often simpler. Kubernetes pays off with many services and a platform team.

You are ready to move on when you can deploy your container to a local cluster (kind or minikube) with probes and limits, scale it, and roll back a bad release.

Key concepts: Pods and Deployments, Services and Ingress, ConfigMaps and Secrets, Liveness and readiness probes, Resource requests and limits, Graceful shutdown on SIGTERM, Horizontal Pod Autoscaler, Helm charts.

Mini project: Deploy your API and Postgres to a kind cluster with a Deployment, Service, Ingress and Secret, add probes, then perform and roll back a rolling update.

Self-check: What is the difference between a failing liveness probe and a failing readiness probe, and what does Kubernetes do in each case?

Resources:
- [Kubernetes Basics tutorial](https://kubernetes.io/docs/tutorials/kubernetes-basics/) (Kubernetes)
- [Kubernetes concepts](https://kubernetes.io/docs/concepts/) (Kubernetes)
- [kind: Quick start](https://kind.sigs.k8s.io/docs/user/quick-start/) (Kubernetes SIGs)

### Reverse Proxies and Load Balancers

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/reverse-proxies-load-balancers

Understand the server that sits in front of your app: TLS termination, routing, load balancing and buffering.

In production, clients rarely talk to your application process directly. A **reverse proxy** accepts the connection and forwards it to one of your app instances. This layer does jobs that application frameworks do poorly or should not do at all.

#### What the front layer does
- **TLS termination**: handles certificates and HTTPS so your app speaks plain HTTP on a private network.
- **Load balancing** across instances with algorithms like round robin, least connections or consistent hashing.
- **Routing** by host or path (`api.example.com` to the API, `/static` to files).
- **Serving static files** and compressing responses efficiently.
- **Buffering** slow clients so your app process is not tied up.
- Basic protection: connection limits, request size limits, rate limiting and timeouts.

#### Layer 4 vs layer 7
- **L4** load balancers route TCP/UDP connections without reading HTTP (fast, protocol-agnostic).
- **L7** load balancers understand HTTP and can route by path, header or cookie, retry, and add headers.
Cloud load balancers (AWS ALB/NLB, Google Cloud Load Balancing) and **HAProxy**, **Nginx**, **Caddy**, **Envoy** or **Traefik** all fill this role.

#### Things your app must handle behind a proxy
- The client IP arrives in `X-Forwarded-For` or `Forwarded`; configure your framework to trust only your proxy.
- The original scheme arrives in `X-Forwarded-Proto`, which matters for redirects and secure cookies.
- **Health checks** from the load balancer decide whether an instance gets traffic.
- WebSockets and long requests need matching timeouts at every hop.

You are ready to move on when you can draw the path of a request from browser to app instance, naming where TLS ends and how the real client IP is preserved.

Key concepts: Forward vs reverse proxy, TLS termination, Load balancing algorithms, L4 vs L7 load balancing, X-Forwarded-For and trusted proxies, Health checks, HAProxy, Envoy and Traefik.

Mini project: Run two instances of your API behind a reverse proxy locally, verify round-robin balancing, log the real client IP correctly, and kill one instance to watch health checks remove it.

Self-check: Why is it dangerous for your app to trust X-Forwarded-For from any client?

Resources:
- [What is a reverse proxy?](https://www.cloudflare.com/learning/cdn/glossary/reverse-proxy/) (Cloudflare)
- [What is load balancing?](https://www.cloudflare.com/learning/performance/what-is-load-balancing/) (Cloudflare)
- [MDN: X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For) (MDN)

### Nginx

recommended · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/nginx

Configure the most widely deployed web server and reverse proxy for your backend.

**Nginx** is an event-driven web server that handles huge numbers of concurrent connections with little memory. It is the most common reverse proxy in front of Node, Python, PHP and Java apps.

#### Configuration structure
Configuration lives in `/etc/nginx/nginx.conf` plus included files. The key blocks:
- `http` holds global settings; each `server` block is a virtual host matched by `listen` and `server_name`.
- `location` blocks match request paths and decide what to do: serve files with `root`/`try_files`, or forward with `proxy_pass`.
- `upstream` groups app instances for load balancing.

#### A typical reverse proxy setup
Define an `upstream api { server 127.0.0.1:3000; server 127.0.0.1:3001; }`, then in a `location /` use `proxy_pass http://api;` with `proxy_set_header Host`, `X-Real-IP` and `X-Forwarded-For`. Add `listen 443 ssl` with certificates (often from Let's Encrypt via certbot) and redirect port 80 to HTTPS.

#### Useful features
- `gzip` or brotli compression, static file caching headers.
- `limit_req` for rate limiting and `client_max_body_size` for upload limits.
- WebSocket proxying (`proxy_http_version 1.1` plus the Upgrade headers).
- Proxy caching for cacheable API responses.

#### Operating it
Always run `nginx -t` to test configuration before `systemctl reload nginx`; reloads are graceful and do not drop connections. Read the access and error logs when requests misbehave; `502 Bad Gateway` means Nginx could not reach your app, `504` means your app was too slow.

You are ready to move on when you can serve a static frontend and proxy `/api` to two app instances over HTTPS with a single Nginx config you wrote yourself.

Key concepts: server and location blocks, proxy_pass and upstreams, TLS with Let's Encrypt, Serving static files, Compression and caching headers, Rate limiting and body size limits, WebSocket proxying, Reading 502 and 504 errors.

Mini project: On a small VPS, configure Nginx to serve a static site, proxy /api to your app with HTTPS from Let's Encrypt, enable gzip and add a rate limit on the login route.

Self-check: Nginx returns 502 Bad Gateway. List the first three things you check.

Resources:
- [Nginx documentation](https://nginx.org/en/docs/) (nginx.org)
- [Nginx beginner's guide](https://nginx.org/en/docs/beginners_guide.html) (nginx.org)
- [Certbot instructions](https://certbot.eff.org/) (EFF)

### Caddy

alternative · beginner · about 2 h · https://www.internhack.in/roadmaps/tracks/backend/caddy

Use Caddy for a reverse proxy with automatic HTTPS and a tiny, readable configuration.

**Caddy** is a modern web server written in Go whose headline feature is **automatic HTTPS**: point a domain at the server, name it in the config, and Caddy obtains and renews certificates from Let's Encrypt or ZeroSSL on its own.

#### The Caddyfile
Configuration is famously short. A full HTTPS reverse proxy can be three lines:
`api.example.com { reverse_proxy localhost:3000 }`
Add `file_server` for static files, `encode gzip zstd` for compression, and `handle_path /api/*` blocks to route by path. Multiple upstreams in `reverse_proxy` enable load balancing with health checks.

#### Why teams choose it
- Secure defaults: modern TLS settings, HTTP/2 and HTTP/3 enabled out of the box.
- Sensible proxy headers (`X-Forwarded-For`, `X-Forwarded-Proto`) set automatically.
- A JSON **admin API** for changing configuration at runtime without restarts.
- Single static binary, easy to run in Docker.

#### Trade-offs
Nginx has a larger ecosystem, more tutorials and more battle-tested niche modules; Caddy plugins require building a custom binary (made easy by `xcaddy`). For small to medium deployments and side projects, Caddy's simplicity usually wins.

#### Pitfalls
- Automatic HTTPS needs ports 80 and 443 reachable and DNS pointing at the server; certificate issuance fails otherwise.
- Persist Caddy's data directory in containers or it will re-request certificates on every restart and hit rate limits.

You are ready to move on when you can serve your app over HTTPS with a Caddyfile, route `/api` to your backend and explain where Caddy stores its certificates.

Key concepts: Caddyfile syntax, Automatic HTTPS, reverse_proxy and load balancing, file_server for static assets, Admin API and JSON config, Running Caddy in Docker.

Mini project: Replace an Nginx config with a Caddyfile that serves your frontend, proxies /api to two backend instances and gets certificates automatically.

Self-check: What two conditions must be true for Caddy's automatic HTTPS to obtain a certificate?

Resources:
- [Caddy documentation](https://caddyserver.com/docs/) (Caddy)
- [Caddy: Getting started](https://caddyserver.com/docs/getting-started) (Caddy)

### Apache HTTP Server

alternative · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/apache-httpd

Work with Apache httpd, still common in PHP hosting, legacy stacks and enterprise environments.

**Apache HTTP Server** (httpd) was the web's dominant server for decades and still runs a large share of sites, especially shared PHP hosting, WordPress installs and older enterprise systems. You are likely to meet it when maintaining existing infrastructure.

#### Key ideas
- **Virtual hosts** (`<VirtualHost *:443>`) serve multiple sites from one server.
- **Modules** add features: `mod_ssl` for TLS, `mod_rewrite` for URL rewriting, `mod_proxy` and `mod_proxy_http` for reverse proxying, `mod_headers` for response headers.
- **MPMs** (multi-processing modules) decide the concurrency model: `prefork` (process per connection, needed by old mod_php setups), `worker` and `event` (threaded, much more efficient). Use `event` with PHP-FPM for modern deployments.
- **.htaccess** files allow per-directory configuration without touching the main config. Convenient on shared hosting, but slower, since Apache checks for them on every request.

#### As a reverse proxy
`ProxyPass "/api" "http://127.0.0.1:3000/"` and `ProxyPassReverse` forward traffic to an app server, and `mod_proxy_balancer` spreads load across several.

#### Operating it
Test with `apachectl configtest` before reloading, and read `error_log` first when something fails. Rewrite rules are powerful but hard to debug; keep them few and commented.

#### When to choose it today
For new projects Nginx or Caddy are usually simpler and more efficient. Apache remains a reasonable choice when you need `.htaccess` compatibility, specific modules, or when your organization already standardizes on it.

You are ready to move on when you can set up a virtual host with TLS that proxies to your app and explain why the event MPM beats prefork for concurrency.

Key concepts: Virtual hosts, Core modules: ssl, rewrite, proxy, MPMs: prefork, worker, event, .htaccess files, PHP-FPM integration, mod_proxy_balancer.

Mini project: Configure Apache with a TLS virtual host that serves static files and proxies /api to your backend, then move a rewrite rule from .htaccess into the main config.

Self-check: Why do .htaccess files slow Apache down, and when are they still worth using?

Resources:
- [Apache HTTP Server documentation](https://httpd.apache.org/docs/current/) (Apache)
- [Apache: Reverse Proxy Guide](https://httpd.apache.org/docs/current/howto/reverse_proxy.html) (Apache)

## Architecture and Design Patterns

Structure code and services so a system stays changeable as the team and traffic grow.

### Monoliths and Modular Monoliths

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/monolith-modular

Build a single deployable application with clear internal boundaries, the right starting point for most products.

A **monolith** is one deployable application containing all features. The word gets used as an insult, but most successful products started as one, and many still are. The real enemy is not the monolith, it is the **big ball of mud**: code where everything calls everything.

#### Why start here
- One codebase, one deploy, one database: easy to develop, test, debug and refactor.
- Function calls instead of network calls: no partial failures, no distributed transactions.
- Small teams move fastest when they do not have to coordinate service contracts.

#### The modular monolith
Keep one deployable, but organize code into **modules by business capability** (billing, catalog, accounts) instead of by technical layer alone:
- Each module has a small **public interface**; other modules may not reach into its internals or its tables.
- Enforce boundaries with folder rules, package visibility or lint rules (for example dependency-cruiser in TypeScript, ArchUnit in Java).
- Communicate between modules through interfaces or in-process events.

#### Layering inside a module
A common arrangement is **controller** (HTTP concerns) to **service** (business logic) to **repository** (data access). Keep business rules out of controllers and SQL out of services so each piece is testable on its own. Hexagonal or "ports and adapters" architecture is a more formal version of the same idea.

#### When a monolith hurts
Very large teams stepping on each other, parts with wildly different scaling or reliability needs, or deploys that take hours. A well-modularized monolith makes extracting a service later straightforward.

You are ready to move on when your project has modules with explicit public interfaces and a check that fails the build if one module imports another's internals.

Key concepts: Monolith vs big ball of mud, Modules by business capability, Controller, service, repository layers, Enforcing module boundaries, Hexagonal architecture (ports and adapters), When to split a monolith.

Mini project: Refactor an existing API into three modules with public interfaces, add a lint rule that forbids cross-module internal imports, and document each module's responsibilities.

Self-check: What is the difference between a monolith and a big ball of mud?

Resources:
- [MonolithFirst](https://martinfowler.com/bliki/MonolithFirst.html) (Martin Fowler)
- [Hexagonal architecture](https://alistair.cockburn.us/hexagonal-architecture/) (Alistair Cockburn)
- [Architecture styles](https://learn.microsoft.com/en-us/azure/architecture/guide/architecture-styles/) (Microsoft Learn)

### Microservices and Service-Oriented Architecture

core · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/microservices-soa

Split a system into independently deployable services and understand the real costs that come with it.

**Microservices** decompose a system into small services, each owning one business capability and its own data, deployed independently and talking over the network. **SOA** (service-oriented architecture) is the older, enterprise-flavored ancestor, often built around a shared enterprise service bus and heavier contracts.

#### What you gain
- Teams deploy on their own schedule without coordinating a release train.
- Services scale independently (the image resizer can have 50 instances, the admin API 2).
- Failures and technology choices can be isolated.

#### What you pay
- **Network calls fail**: timeouts, retries and partial failure are now normal (see resilience patterns).
- **Data is distributed**: no joins across services and no simple transactions. You use events, sagas and eventual consistency.
- **Operational overhead**: many pipelines, dashboards, versions and on-call surfaces. Observability becomes mandatory.
- **Contract management**: breaking an API now breaks another team.

#### Design guidelines
- Split by **business capability or bounded context**, not by technical layer ("the database service" is an anti-pattern).
- **Database per service**: other services go through the API, never directly to your tables.
- Prefer **asynchronous events** for notifications between services and synchronous calls (REST, gRPC) only when an answer is needed now.
- An **API gateway** handles cross-cutting concerns (auth, rate limiting, routing) at the edge.

#### The distributed monolith
Services that must be deployed together, share a database, or call each other in long synchronous chains have all the costs of microservices and none of the benefits.

You are ready to move on when you can take a monolith's modules, argue which (if any) should become services, and describe how they would communicate and own data.

Key concepts: Service boundaries by capability, Database per service, Sync vs async communication, API gateway, Service discovery, Sagas for distributed workflows, SOA and enterprise service bus, Distributed monolith anti-pattern.

Mini project: Extract one module (for example notifications) from your monolith into a separate service with its own database, communicating through an event queue, and document the failure modes you had to handle.

Self-check: Two services share one database schema. Why does that undermine the main benefit of microservices?

Resources:
- [Microservices](https://martinfowler.com/articles/microservices.html) (Martin Fowler)
- [Microservice Architecture patterns](https://microservices.io/) (Chris Richardson)
- [Microservices architecture style](https://learn.microsoft.com/en-us/azure/architecture/guide/architecture-styles/microservices) (Microsoft Learn)

### Serverless and Functions as a Service

recommended · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/serverless

Run backend code as on-demand functions and managed services, paying per request instead of per server.

**Serverless** means you deploy code or use services without managing servers or capacity: the platform runs your code when events arrive and bills per invocation. **Functions as a Service** (AWS Lambda, Google Cloud Run functions, Azure Functions, Cloudflare Workers, Vercel functions) is the most visible part; managed databases, queues and storage complete the picture.

#### How it works
- A function is triggered by an **event**: an HTTP request through an API gateway, a new file in a bucket, a message on a queue, a cron schedule.
- The platform starts an instance, runs your handler, and may reuse the warm instance for later events or scale out to thousands in parallel.
- You pay for execution time and requests; idle costs nothing.

#### Strengths
Spiky or low traffic, event-driven glue (resize images on upload, process webhooks), scheduled jobs, and teams that want zero server maintenance.

#### Constraints to design around
- **Cold starts**: the first invocation on a new instance is slower. Keep bundles small and initialize clients outside the handler.
- **Statelessness**: local memory and disk are temporary; state goes in databases or storage.
- **Time and size limits** on execution and payloads.
- **Database connections**: many parallel instances can exhaust a database, so use a pooler or an HTTP-based database driver.
- **Vendor lock-in** and harder local debugging; frameworks like SST or the Serverless Framework help.
- Costs can exceed a plain server at steady high load.

#### Edge functions
Workers and edge runtimes run code in CDN locations close to users with near-zero cold starts, but with restricted APIs (no arbitrary TCP, limited Node compatibility).

You are ready to move on when you have deployed an HTTP function and a queue-triggered function, measured a cold start, and can state when a container would be cheaper.

Key concepts: Event triggers, Cold starts and warm instances, Stateless handlers, Database connections from functions, Edge functions and Workers, Cost model vs containers, Infrastructure as code for serverless.

Mini project: Build a serverless image pipeline: an upload to object storage triggers a function that creates thumbnails and writes metadata to a database, with an HTTP function to list results.

Self-check: Why should you create your database client outside the function handler rather than inside it?

Resources:
- [What is AWS Lambda?](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) (AWS)
- [Cloudflare Workers documentation](https://developers.cloudflare.com/workers/) (Cloudflare)
- [Serverless Architectures](https://martinfowler.com/articles/serverless.html) (Martin Fowler)

### Twelve-Factor Apps and Cloud-Native Habits

core · intermediate · about 2 h · https://www.internhack.in/roadmaps/tracks/backend/twelve-factor-apps

Follow the conventions that make a service easy to deploy, scale and operate on any modern platform.

**The Twelve-Factor App** is a short methodology, written by Heroku engineers, describing how to build services that run cleanly on cloud platforms. Most modern deployment tools (containers, Kubernetes, PaaS) assume you follow it.

#### The factors that matter most day to day
- **Codebase**: one repo per app, many deploys (dev, staging, prod) from it.
- **Dependencies**: declared explicitly in a manifest and lockfile; nothing assumed to be preinstalled.
- **Config** in the environment: URLs, credentials and flags come from environment variables, never from code. The same build runs in every environment.
- **Backing services** (databases, queues, email) are attached resources swapped by changing config.
- **Build, release, run** are separate stages; a release is an immutable build plus config.
- **Processes** are stateless and share nothing; state lives in backing services.
- **Port binding**: the app is self-contained and exposes HTTP on a port.
- **Concurrency**: scale out by running more processes.
- **Disposability**: fast startup and graceful shutdown on SIGTERM.
- **Dev/prod parity**: keep environments similar (containers help).
- **Logs** as event streams to stdout; the platform collects them.
- **Admin processes** (migrations, one-off scripts) run as one-off processes against the same release.

#### Beyond the original twelve
Modern teams add: health check endpoints, structured logs, metrics and traces, secure-by-default dependencies, and API-first design.

#### Pitfalls
- Config files per environment committed to the repo with secrets inside.
- Writing uploads or sessions to local disk, which breaks the moment you scale to two instances.

You are ready to move on when you can audit your own service against each factor and fix at least the config, logs, statelessness and disposability ones.

Key concepts: Config in environment variables, Stateless processes, Build, release, run, Disposability and graceful shutdown, Logs as event streams, Dev/prod parity, Admin processes.

Mini project: Audit one of your services against all twelve factors in a checklist, then fix the three biggest gaps and note what changed.

Self-check: Why does storing user sessions in process memory violate twelve-factor principles, and what breaks in practice?

Resources:
- [The Twelve-Factor App](https://12factor.net/) (12factor.net)
- [Cloud Native Computing Foundation glossary](https://glossary.cncf.io/) (CNCF)

### Service Mesh

optional · advanced · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/service-mesh

Move service-to-service concerns like mTLS, retries and traffic splitting out of code and into infrastructure.

In a system with dozens of microservices, every service needs the same plumbing: encrypted connections, retries, timeouts, metrics and gradual rollouts. A **service mesh** provides this at the infrastructure layer so application code does not have to.

#### How it works
- A **data plane** of proxies (usually **Envoy** sidecars next to each pod, or node-level proxies in newer "ambient" or sidecarless modes) intercepts all traffic between services.
- A **control plane** (Istio, Linkerd, Consul) configures those proxies from high-level policies.

#### What you get
- **Mutual TLS** between services automatically, with identity per service, enabling zero-trust networking.
- **Traffic management**: retries, timeouts, circuit breaking and **traffic splitting** for canary releases (send 5 percent to v2).
- **Observability**: golden metrics (requests, errors, latency) and trace propagation for every call without code changes.
- **Authorization policies**: "only the checkout service may call the payments service".

#### The cost
A mesh adds latency per hop, memory per proxy and a significant amount of operational complexity. Debugging now includes the mesh configuration. For a handful of services, a good HTTP client library with timeouts and retries plus a gateway is usually enough.

#### When it is worth it
Many services owned by many teams on Kubernetes, compliance requirements for encrypted internal traffic, or a platform team ready to own it.

You are ready to move on when you can explain what a sidecar proxy does to a request, and list two problems a mesh solves and two it creates.

Key concepts: Data plane and control plane, Sidecar proxies (Envoy), Mutual TLS between services, Traffic splitting and canaries, Istio vs Linkerd, Sidecarless and ambient modes.

Mini project: Install Linkerd on a local kind cluster with two services, confirm mTLS is active, and run a 90/10 traffic split between two versions.

Self-check: What does a service mesh give you that a shared HTTP client library cannot?

Resources:
- [Istio documentation](https://istio.io/latest/docs/) (Istio)
- [Linkerd documentation](https://linkerd.io/docs/) (Linkerd)
- [Envoy proxy documentation](https://www.envoyproxy.io/docs) (Envoy)

### Design Patterns for Backend Code

recommended · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/design-patterns-gof

Use classic Gang of Four and enterprise patterns to structure code, and recognize when they are overkill.

**Design patterns** are named, reusable solutions to recurring design problems. Knowing them gives you vocabulary ("wrap it in an adapter") and ready-made shapes, as long as you apply them to real problems rather than to show off.

#### Gang of Four patterns you will actually use
- **Strategy**: swap algorithms behind an interface (different pricing or shipping calculators).
- **Adapter**: wrap a third-party API (a payment provider) behind your own interface so it can be replaced and mocked.
- **Factory**: centralize object creation when the concrete type depends on input or config.
- **Decorator**: add behavior (caching, logging, retries) around an object without changing it; HTTP middleware is the same idea.
- **Observer**: notify subscribers of events; the basis of in-process event emitters.
- **Singleton**: one shared instance (a DB pool). Use sparingly; it becomes hidden global state that complicates tests.
- **Builder** and **Facade** for complex construction and simplifying a messy subsystem.

#### Enterprise application patterns
- **Repository**: a collection-like interface over data access, keeping SQL out of business logic.
- **Unit of Work**: track changes and commit them in one transaction (what most ORMs do).
- **Dependency injection**: pass collaborators in rather than creating them inside, which makes testing easy. Frameworks like NestJS, Spring and ASP.NET build on it.
- **Middleware / chain of responsibility** for request pipelines.

#### Principles behind them
**SOLID**, composition over inheritance, and "program to an interface" explain why the patterns work.

#### Pitfalls
Pattern-itis: factories of factories and interfaces with one implementation that never changes. Start simple and refactor to a pattern when the pain appears.

You are ready to move on when you can spot three patterns in your framework of choice and refactor one piece of your code to use Adapter or Strategy with a test proving the swap works.

Key concepts: Strategy and Adapter, Factory and Builder, Decorator and middleware, Observer, Repository and Unit of Work, Dependency injection, SOLID principles, Singleton and its pitfalls.

Mini project: Wrap two email providers behind one Adapter interface, select between them with a Strategy based on config, inject it into your service, and unit test the service with a fake.

Self-check: How does HTTP middleware relate to the Decorator and Chain of Responsibility patterns?

Resources:
- [Refactoring.Guru: Design Patterns](https://refactoring.guru/design-patterns) (Refactoring.Guru)
- [Catalog of Patterns of Enterprise Application Architecture](https://martinfowler.com/eaaCatalog/) (Martin Fowler)
- [Inversion of Control Containers and the Dependency Injection pattern](https://martinfowler.com/articles/injection.html) (Martin Fowler)

### Domain-Driven Design

optional · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/domain-driven-design

Model complex business domains with a shared language, bounded contexts and aggregates that protect invariants.

**Domain-Driven Design** (DDD) is an approach for software where the hard part is the business logic, not the technology: insurance, logistics, banking, marketplaces. It gives you tools to model that logic together with domain experts.

#### Strategic design
- **Ubiquitous language**: developers and domain experts use the same terms, and those terms appear in the code. If the business says "policy" and "claim", your classes do too.
- **Bounded contexts**: a large domain is split into areas where each term has one precise meaning. "Customer" in billing (payment details) differs from "customer" in support (tickets). Each context has its own model, and often maps to a module or service.
- **Context maps** describe how contexts relate, including **anti-corruption layers** that translate another system's model so it does not leak into yours.

#### Tactical design
- **Entities** have identity (an order with an id); **value objects** are defined by their values and are immutable (`Money(100, "INR")`, an address).
- **Aggregates** group entities that must stay consistent together, with one **aggregate root** as the only entry point. Invariants ("an order total cannot be negative") are enforced inside the aggregate, and one transaction changes one aggregate.
- **Domain events** record things that happened ("OrderPlaced") and let other parts react.
- **Repositories** load and save whole aggregates; **domain services** hold logic that fits no single entity.

#### When DDD pays off
Rich, changing business rules and long-lived systems. For CRUD apps it is heavy ceremony; borrow the ubiquitous language and bounded contexts and skip the rest.

You are ready to move on when you can identify the bounded contexts of a familiar business, name one aggregate with its invariants, and explain why it should be modified in a single transaction.

Key concepts: Ubiquitous language, Bounded contexts and context maps, Entities and value objects, Aggregates and invariants, Domain events, Anti-corruption layer, Event storming workshops.

Mini project: Model an order-fulfilment domain: define two bounded contexts, an Order aggregate with invariants enforced in code, a Money value object and an OrderPlaced domain event, all covered by unit tests.

Self-check: Why should a single transaction typically modify only one aggregate?

Resources:
- [Domain Driven Design](https://martinfowler.com/bliki/DomainDrivenDesign.html) (Martin Fowler)
- [Bounded Context](https://martinfowler.com/bliki/BoundedContext.html) (Martin Fowler)
- [Using domain analysis to model microservices](https://learn.microsoft.com/en-us/azure/architecture/microservices/model/domain-analysis) (Microsoft Learn)

### CQRS and Event Sourcing

optional · advanced · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/cqrs-event-sourcing

Separate read and write models, and store state as a log of events, for domains that truly need it.

These two patterns often appear together but are independent. Both are powerful and both add real complexity, so treat them as tools for specific problems.

#### CQRS
**Command Query Responsibility Segregation** splits the **write model** (commands that change state and enforce rules) from the **read model** (queries shaped for screens). The read side can be a denormalized table, a cache or a search index that is updated when the write side changes.
- Useful when reads and writes have very different shapes or loads, such as a dashboard aggregating data that is written in small transactions.
- A light version is common and cheap: separate query functions that bypass the domain model and read straight from optimized views.
- The heavy version, with separate databases, means reads are **eventually consistent** with writes.

#### Event sourcing
Instead of storing only the current state (`balance = 70`), you store every **event** that led to it (`Deposited 100`, `Withdrew 30`) in an append-only **event store**. Current state is derived by replaying events, usually accelerated with **snapshots** and **projections** (read models built from the event stream).
- Gains: a complete audit trail, the ability to rebuild read models or answer new questions about the past, and natural integration events.
- Costs: event schema evolution (old events live forever), harder queries, eventual consistency, and a steep learning curve.

#### When to use them
Finance, ledgers, compliance-heavy domains, collaborative editing and complex workflows. For a typical CRUD API, an audit log table plus well-designed queries gives most of the benefit.

#### Related
The **transactional outbox** pattern reliably publishes events after a database write without two-phase commit.

You are ready to move on when you can build a small event-sourced bank account with a projection for the current balance and explain how you would change an event's shape later.

Key concepts: Commands vs queries, Separate read models, Event store and append-only logs, Projections and snapshots, Event versioning and upcasting, Eventual consistency in the UI, Transactional outbox.

Mini project: Implement an event-sourced wallet: commands append events to a Postgres table, a projection maintains balances, and a rebuild script regenerates the projection from scratch.

Self-check: What problem does event sourcing solve that a simple audit log table does not, and what new problem does it create?

Resources:
- [CQRS](https://martinfowler.com/bliki/CQRS.html) (Martin Fowler)
- [Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html) (Martin Fowler)
- [CQRS pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrs) (Microsoft Learn)

## Background Jobs and Message Brokers

Move slow or unreliable work out of the request path and let services communicate through queues and event streams.

### Background Jobs and Task Queues

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/background-jobs

Run slow, retryable or scheduled work in worker processes instead of making users wait.

A request should do the minimum needed to answer the user. Sending emails, generating PDFs, resizing images, calling slow third-party APIs and nightly reports belong in **background jobs** processed by separate **worker** processes.

#### The basic shape
1. The web process **enqueues** a job (`sendWelcomeEmail`, `{ userId: 42 }`) and responds immediately.
2. A **queue** stores the job durably. Redis-backed libraries are the common choice: **BullMQ** (Node), **Celery** or RQ (Python), **Sidekiq** (Ruby), Hangfire (.NET). Postgres-backed queues (pg-boss, Graphile Worker, Oban) avoid an extra system.
3. One or more **workers** pull jobs, run them and mark them done.

#### Designing reliable jobs
- **Retries with exponential backoff** for transient failures, with a max attempt count.
- A **dead-letter queue** (or failed set) for jobs that keep failing, plus alerting on it.
- **Idempotency**: jobs can run more than once (a worker crashes after finishing but before acknowledging). Design them so a second run is harmless.
- Pass **ids, not objects**: the worker loads fresh data rather than a stale snapshot.
- **Timeouts** so a hung job does not block a worker forever.

#### Scheduling and priorities
Cron-style **recurring jobs**, **delayed jobs** ("remind in 24 hours"), separate queues for priorities so bulk exports do not delay password resets, and **concurrency limits** to protect rate-limited APIs.

#### Enqueue safely
If you enqueue inside a database transaction that later rolls back, the job runs for data that does not exist. Enqueue after commit, or use a DB-backed queue or the transactional outbox pattern.

You are ready to move on when your app sends email from a worker with retries and a dead-letter view, and you can explain what happens if the worker crashes mid-job.

Key concepts: Producers, queues and workers, Retries and exponential backoff, Dead-letter queues, Idempotent jobs, Scheduled and delayed jobs, Priorities and concurrency limits, BullMQ, Celery, Sidekiq, Database-backed queues.

Mini project: Add a job queue to your API for report generation: enqueue on request, process in a worker with retries, expose job status via an endpoint and show failed jobs in a small admin view.

Self-check: A job charges a customer and then the worker crashes before acknowledging it. What happens next, and how do you make that safe?

Resources:
- [BullMQ documentation](https://docs.bullmq.io/) (BullMQ)
- [Celery documentation](https://docs.celeryq.dev/) (Celery)
- [Background jobs guidance](https://learn.microsoft.com/en-us/azure/architecture/best-practices/background-jobs) (Microsoft Learn)

### Messaging Patterns and Delivery Guarantees

core · intermediate · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/messaging-fundamentals

Understand queues vs pub/sub, delivery semantics, ordering and the outbox pattern before choosing a broker.

A **message broker** lets services communicate without calling each other directly. The producer sends a message and moves on; consumers process it when they can. This decouples services in time and load, but introduces new failure modes you must reason about.

#### Two core patterns
- **Point-to-point queue**: each message is handled by exactly one consumer from a pool. Used for distributing work ("process this order").
- **Publish/subscribe**: each message goes to every subscriber. Used for broadcasting facts ("OrderPlaced") to billing, email and analytics independently.

#### Delivery guarantees
- **At-most-once**: may lose messages, never duplicates.
- **At-least-once**: never loses acknowledged messages, may deliver duplicates. The practical default.
- **Exactly-once** is only achievable within specific systems and boundaries; across your whole pipeline you get it by combining at-least-once delivery with **idempotent consumers** (track processed message ids).

#### Ordering and failures
Ordering is usually guaranteed only within a queue or partition, not globally. Design so that consumers can handle out-of-order or late messages, for example by carrying versions or timestamps. **Poison messages** that always fail must go to a dead-letter queue, not loop forever.

#### The dual-write problem
Writing to your database and publishing to the broker are two separate operations; one can succeed while the other fails. The **transactional outbox** fixes it: write the event to an `outbox` table in the same transaction as the business data, and a relay publishes it afterwards. **Change data capture** (Debezium) is a related technique.

#### Commands vs events
A **command** asks for something ("SendInvoice") and has one handler; an **event** states a fact ("InvoicePaid") and may have many.

You are ready to move on when you can explain at-least-once delivery, write an idempotent consumer and sketch the outbox pattern.

Key concepts: Queues vs publish/subscribe, At-least-once delivery, Idempotent consumers, Ordering guarantees, Poison messages and DLQs, Transactional outbox, Change data capture, Commands vs events.

Mini project: Implement the outbox pattern in your app: write OrderPlaced to an outbox table in the order transaction, relay it to a queue, and build a consumer that ignores duplicates.

Self-check: Why is 'exactly-once delivery' across services achieved in practice with at-least-once delivery plus idempotency?

Resources:
- [Enterprise Integration Patterns](https://www.enterpriseintegrationpatterns.com/) (Gregor Hohpe)
- [Pattern: Transactional outbox](https://microservices.io/patterns/data/transactional-outbox.html) (microservices.io)
- [Debezium documentation](https://debezium.io/documentation/) (Debezium)

### RabbitMQ

recommended · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/rabbitmq

Route messages between services with exchanges, queues and acknowledgements in the classic message broker.

**RabbitMQ** is a mature, general-purpose message broker implementing AMQP 0-9-1. It shines at task distribution and flexible routing between services, and it is easy to run locally.

#### The routing model
Producers never publish directly to queues. They publish to an **exchange**, which routes messages to **queues** based on **bindings**:
- **Direct** exchanges route by exact routing key (`email.send`).
- **Topic** exchanges route by pattern (`order.*.created`, `order.#`).
- **Fanout** exchanges copy every message to all bound queues (pub/sub).
- **Headers** exchanges route by message headers (rare).
Consumers subscribe to queues. Several consumers on one queue share the work.

#### Reliability settings
- **Durable queues** and **persistent messages** survive broker restarts.
- **Manual acknowledgements**: the consumer acks only after finishing; unacked messages are redelivered if it dies.
- **Prefetch (QoS)** limits how many unacked messages each consumer holds, balancing load fairly.
- **Publisher confirms** tell the producer the broker safely stored the message.
- **Dead-letter exchanges** catch rejected or expired messages.
- **Quorum queues** replicate data across a cluster for high availability and are the modern default over classic mirrored queues.

#### When to pick RabbitMQ
Work queues, request/reply, complex routing and moderate throughput where each message is consumed and removed. For replayable, very high-volume event streams, Kafka fits better. RabbitMQ also offers **Streams** for log-style use cases.

#### Pitfalls
- Auto-ack mode silently losing messages when a consumer crashes.
- Unbounded queues growing because consumers are down, until memory alarms block publishers.

You are ready to move on when you can set up a topic exchange feeding two queues, process messages with manual acks and prefetch, and route failures to a dead-letter queue.

Key concepts: Exchanges, queues and bindings, Direct, topic and fanout exchanges, Manual acks and prefetch, Durability and publisher confirms, Dead-letter exchanges, Quorum queues, Management UI and monitoring.

Mini project: Run RabbitMQ in Docker and build an order pipeline: the API publishes order events to a topic exchange, separate email and inventory consumers process them with manual acks, and failures land in a dead-letter queue.

Self-check: What is the difference between a fanout and a topic exchange, and when would you use each?

Resources:
- [RabbitMQ tutorials](https://www.rabbitmq.com/tutorials) (RabbitMQ)
- [RabbitMQ documentation](https://www.rabbitmq.com/docs) (RabbitMQ)

### Event Streaming with Apache Kafka

recommended · advanced · about 8 h · https://www.internhack.in/roadmaps/tracks/backend/kafka

Use Kafka's durable, partitioned log for high-throughput event streams that many consumers can replay.

**Apache Kafka** is a distributed **commit log**. Instead of deleting messages once consumed, it stores them for a configured retention period, and any number of consumers read the log at their own pace. That makes it the backbone of event-driven architectures, analytics pipelines and change-data-capture at many large companies.

#### Core concepts
- A **topic** is a named stream of records, split into **partitions** for parallelism. Each partition is an ordered, append-only log replicated across **brokers**.
- Records have a **key**; records with the same key go to the same partition, so ordering is guaranteed **per key** (all events for order 42 stay in order).
- **Consumer groups** share partitions: each partition is read by exactly one consumer in the group, so the partition count caps parallelism.
- Consumers track their position with **offsets**, so they can **replay** from any point, for example to rebuild a read model.

#### Reliability knobs
- Producer `acks=all` with replication factor 3 and `min.insync.replicas=2` for durability.
- **Idempotent producers** and transactions reduce duplicates within Kafka.
- Commit offsets **after** processing (at-least-once) and keep consumers idempotent.

#### Ecosystem
**Kafka Connect** moves data between Kafka and databases or storage, **Kafka Streams** and Flink process streams, and a **schema registry** (Avro, Protobuf, JSON Schema) keeps producers and consumers compatible. Modern Kafka runs without ZooKeeper using **KRaft**. Managed services and compatible alternatives (Confluent Cloud, Amazon MSK, Redpanda) reduce operational load.

#### When not to use it
Simple task queues with low volume, or teams without capacity to operate it. A job queue or RabbitMQ is simpler there.

You are ready to move on when you can produce keyed events to a multi-partition topic, consume them with a consumer group, and replay from an earlier offset.

Key concepts: Topics, partitions and brokers, Keys and per-partition ordering, Consumer groups, Offsets and replay, Retention and compacted topics, Producer acks and durability, Schema registry, Kafka Connect and stream processing.

Mini project: Run Kafka locally with KRaft, publish order events keyed by order id to a 3-partition topic, run two consumers in a group, then add a new consumer group that replays history to build a report.

Self-check: Your topic has 4 partitions and you start 6 consumers in the same group. What happens and why?

Resources:
- [Apache Kafka documentation](https://kafka.apache.org/documentation/) (Apache)
- [Apache Kafka quickstart](https://kafka.apache.org/quickstart) (Apache)
- [Confluent Developer courses](https://developer.confluent.io/) (Confluent)

## Real-Time Communication

Push data to clients as it changes with WebSockets, Server-Sent Events and polling.

### WebSockets

recommended · intermediate · about 6 h · https://www.internhack.in/roadmaps/tracks/backend/websockets

Keep a persistent, two-way connection open for chat, multiplayer, live collaboration and dashboards.

HTTP is request/response: the client asks, the server answers. For chat, live cursors or multiplayer games the server needs to push data the instant it happens. **WebSockets** upgrade an HTTP connection into a persistent, full-duplex channel where both sides can send messages at any time.

#### How it works
The client sends an HTTP request with `Upgrade: websocket`; the server replies `101 Switching Protocols` and the TCP connection stays open, carrying small framed messages (text or binary). Use `wss://` (TLS) in production.

#### Building with it
- Low-level libraries: `ws` (Node), `websockets` (Python), Gorilla or `nhooyr` (Go).
- Higher-level frameworks add rooms, reconnection, acknowledgements and fallbacks: **Socket.IO**, SignalR (.NET), Phoenix Channels, Django Channels. Socket.IO uses its own protocol, so its clients and servers must match.
- Define a message **protocol**: a `type` field plus payload, versioned like an API.

#### Auth and security
Authenticate during the handshake (cookie or a short-lived token), check the `Origin` header to prevent cross-site WebSocket hijacking, validate every incoming message like any other input, and rate limit messages per connection.

#### Scaling
Each connection lives on one server, so:
- Use a **pub/sub backplane** (Redis pub/sub, NATS) so a message published on server A reaches users connected to server B.
- Configure load balancers and proxies for long-lived connections (timeouts, Upgrade headers); sticky sessions may be needed for some libraries.
- Send **heartbeats** (ping/pong) to detect dead connections, and have clients reconnect with backoff and resync missed state.

You are ready to move on when you can build a chat room that works across two server instances behind a load balancer and survives a client reconnect.

Key concepts: Upgrade handshake and frames, Message protocol design, Authenticating connections, Origin checks and input validation, Heartbeats and reconnection, Scaling with a pub/sub backplane, Socket.IO and similar frameworks.

Mini project: Build a multi-room chat with WebSockets that authenticates on connect, uses Redis pub/sub to work across two instances, and shows typing indicators and presence.

Self-check: Two users are connected to different server instances. How does a message from one reach the other?

Resources:
- [MDN: The WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) (MDN)
- [RFC 6455: The WebSocket Protocol](https://datatracker.ietf.org/doc/html/rfc6455) (IETF)
- [Socket.IO documentation](https://socket.io/docs/v4/) (Socket.IO)

### Server-Sent Events and Polling

recommended · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/sse-and-polling

Choose the simplest real-time technique that works: short polling, long polling or one-way SSE streams.

Not every live feature needs WebSockets. If data only flows **from server to client** (notifications, progress bars, live scores, streaming AI responses), simpler options are easier to build, cache and scale.

#### Short polling
The client asks every N seconds: `GET /jobs/42/status`. Trivial to implement and works everywhere, but wastes requests when nothing changes and adds up to N seconds of delay. Perfectly fine for dashboards refreshing every 30 seconds. Use ETags so unchanged responses are cheap.

#### Long polling
The client makes a request and the server **holds it open** until there is new data or a timeout (say 30 seconds), then the client immediately asks again. Near real-time with plain HTTP, but each waiting client ties up a connection, and you must handle timeouts carefully.

#### Server-Sent Events
**SSE** keeps one HTTP response open and streams events in a simple text format (`event:`, `data:`, `id:` lines). The browser's `EventSource` API handles it natively and **reconnects automatically**, sending `Last-Event-ID` so the server can resume. It works through most proxies and over HTTP/2, where many streams share one connection.
Limits: one-way only (client-to-server still uses normal requests), text only, and over HTTP/1.1 browsers cap connections per domain.

#### Choosing
- Occasional updates, low urgency: **short polling**.
- One-way live updates, streaming responses: **SSE**.
- Frequent two-way messages, low latency: **WebSockets**.
Webhooks cover the server-to-server version of the same problem.

#### Pitfalls
Proxies that buffer responses break SSE; disable buffering (for example `X-Accel-Buffering: no` in Nginx) and send periodic comment lines as keep-alives.

You are ready to move on when you can stream job progress to a browser over SSE with automatic resume after a disconnect, and justify SSE vs WebSockets for a given feature.

Key concepts: Short polling, Long polling, Server-Sent Events format, EventSource and automatic reconnect, Last-Event-ID resume, Proxy buffering pitfalls, Choosing SSE vs WebSockets.

Mini project: Build a report-export feature that streams progress percentages over SSE, resumes correctly after a network drop, and falls back to polling a status endpoint.

Self-check: Why is SSE a better fit than WebSockets for streaming an AI model's response token by token?

Resources:
- [MDN: Using server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) (MDN)
- [HTML Standard: Server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html) (WHATWG)

## Observability and Performance

See what your system is doing in production through logs, metrics and traces, and find out where time goes.

### Structured Logging

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/structured-logging

Emit machine-readable logs with context so you can search, filter and correlate them during an incident.

Logs are the first thing you open when something breaks. `console.log("error!")` scattered around the code will not help at 3 a.m. with ten instances running. Good logging is deliberate.

#### Structure, not prose
Write logs as **JSON objects** with consistent fields instead of free text:
`{"level":"error","msg":"payment failed","orderId":42,"provider":"stripe","requestId":"a1b2","durationMs":812}`
Now you can query "all errors for order 42" or "p95 duration by provider". Libraries: **pino** or winston (Node), structlog or the stdlib `logging` with a JSON formatter (Python), `slog` or zap (Go), Logback/SLF4J (Java), Serilog (.NET).

#### Levels and context
- Use levels meaningfully: `debug` for development detail, `info` for notable business events, `warn` for recoverable oddities, `error` for failures needing attention.
- Attach a **request id** (or trace id) to every log line in a request, usually via middleware and async context, so you can follow one request across services.
- Log at boundaries: incoming request, outgoing calls, job start and end, and every caught error with its stack.

#### Where logs go
Following twelve-factor, write to **stdout** and let the platform ship logs to a central store: Loki, Elasticsearch/OpenSearch, CloudWatch, Datadog and similar. Set **retention** and sampling to control cost.

#### Pitfalls
- Logging secrets, tokens, passwords or full card numbers. Redact fields centrally.
- Logging personal data you are not allowed to retain.
- So much noise at `info` that real problems drown; review logs like code.

You are ready to move on when every request in your app produces JSON logs with a request id, errors include stack traces, and sensitive fields are redacted automatically.

Key concepts: JSON structured logs, Log levels, Request and correlation ids, Redacting sensitive data, Centralized log storage, Retention and sampling.

Mini project: Add structured logging with a request id middleware to your API, redact auth headers and passwords, ship logs to a local Loki or OpenSearch and query all logs for one failing request.

Self-check: Why is a request id in every log line so valuable when you have many instances or services?

Resources:
- [OWASP Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html) (OWASP)
- [The Twelve-Factor App: Logs](https://12factor.net/logs) (12factor.net)
- [Pino documentation](https://getpino.io/) (Pino)

### Metrics, Dashboards and Alerting

core · intermediate · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/metrics-alerting

Measure rates, errors and latency with Prometheus-style metrics, build dashboards and alert on user-visible symptoms.

Logs tell you what happened to one request; **metrics** tell you how the whole system is behaving right now. They are cheap numeric time series you can graph and alert on.

#### Metric types
- **Counter**: only goes up (`http_requests_total`). You graph its rate.
- **Gauge**: goes up and down (`queue_depth`, `db_pool_in_use`).
- **Histogram**: buckets of observed values (`http_request_duration_seconds`) so you can compute percentiles.
Add **labels** (route, method, status code) but keep them low-cardinality; a label per user id can take down your metrics system.

#### What to measure
- **RED** for services: **R**ate, **E**rrors, **D**uration of requests.
- **USE** for resources: **U**tilization, **S**aturation, **E**rrors of CPU, memory, disks, pools.
- Google's **four golden signals**: latency, traffic, errors, saturation.
- Business metrics too: signups, checkouts, failed payments.

#### Percentiles, not averages
An average latency of 100 ms can hide a p99 of 5 seconds that frustrates your best customers. Watch **p50, p95 and p99**.

#### Tooling
**Prometheus** scrapes a `/metrics` endpoint from each instance and stores time series; **Grafana** builds dashboards. Hosted options include Grafana Cloud, Datadog and CloudWatch. OpenTelemetry can export metrics to any of them.

#### Alerting well
- Alert on **symptoms users feel** (error rate above 2 percent, p99 above 1 s) rather than every cause (CPU at 80 percent).
- Define **SLOs** (for example 99.9 percent of requests succeed) and alert on error-budget burn rate.
- Every alert should be actionable and link to a runbook; noisy alerts get ignored.

You are ready to move on when your service exposes RED metrics, a Grafana dashboard shows p95 latency per route, and one symptom-based alert fires in a test.

Key concepts: Counters, gauges and histograms, Labels and cardinality, RED and USE methods, Percentile latency, Prometheus and Grafana, SLIs, SLOs and error budgets, Symptom-based alerting and runbooks.

Mini project: Instrument your API with request count and latency histograms, run Prometheus and Grafana with Docker Compose, build a RED dashboard and configure an alert for a high error rate.

Self-check: Why is alerting on high CPU usually worse than alerting on elevated error rate or latency?

Resources:
- [Prometheus: Overview](https://prometheus.io/docs/introduction/overview/) (Prometheus)
- [SRE Book: Monitoring Distributed Systems](https://sre.google/sre-book/monitoring-distributed-systems/) (Google)
- [Grafana documentation](https://grafana.com/docs/grafana/latest/) (Grafana Labs)

### Distributed Tracing with OpenTelemetry

recommended · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/distributed-tracing-otel

Follow a single request across services, queues and databases to see exactly where time and errors come from.

When a request touches an API gateway, three services, a queue and two databases, neither logs nor metrics alone show where the 2 seconds went. **Distributed tracing** records the request's full path.

#### Traces and spans
- A **trace** represents one end-to-end operation and has a **trace id**.
- It is made of **spans**: timed units of work (an HTTP handler, a SQL query, an outgoing call) with a parent-child structure, attributes and status.
- A trace viewer shows spans as a waterfall, making slow or failing steps obvious.

#### Context propagation
For spans from different services to join one trace, the trace context must travel with the request. The W3C **traceparent** header does this for HTTP; message headers do it for queues. Instrumentation libraries inject and extract it automatically.

#### OpenTelemetry
**OpenTelemetry** (OTel) is the vendor-neutral standard for traces, metrics and logs:
- **SDKs** and **auto-instrumentation** for most languages capture HTTP servers, clients, database drivers and queue libraries with little code.
- You add **custom spans** around important business logic.
- The **OTel Collector** receives telemetry, processes it (batching, sampling, redaction) and exports it to backends like **Jaeger**, Grafana Tempo, Zipkin, Honeycomb or Datadog. Switching vendors becomes a config change.

#### Sampling
Recording every trace is expensive at scale. **Head sampling** keeps a percentage chosen at the start; **tail sampling** decides after the trace completes, so you can keep all errors and slow requests.

#### Connecting signals
Put the trace id in your logs and link metrics exemplars to traces, so you can jump from a latency spike to an example trace to its logs.

You are ready to move on when a request through two of your services shows up as one trace in Jaeger, including the database query spans, and your logs carry the same trace id.

Key concepts: Traces and spans, Context propagation and traceparent, OpenTelemetry SDKs and auto-instrumentation, Custom spans and attributes, OpenTelemetry Collector, Head vs tail sampling, Jaeger and Grafana Tempo, Correlating logs, metrics and traces.

Mini project: Add OpenTelemetry auto-instrumentation to two services and a queue consumer, export through a Collector to Jaeger, and find the slowest span in a deliberately slow endpoint.

Self-check: How does a downstream service know which trace an incoming request belongs to?

Resources:
- [OpenTelemetry documentation](https://opentelemetry.io/docs/) (OpenTelemetry)
- [OpenTelemetry: Traces](https://opentelemetry.io/docs/concepts/signals/traces/) (OpenTelemetry)
- [Jaeger documentation](https://www.jaegertracing.io/docs/) (Jaeger)

### Performance Profiling and Load Testing

recommended · advanced · about 5 h · https://www.internhack.in/roadmaps/tracks/backend/performance-profiling

Find real bottlenecks with profilers and load tests instead of guessing, then fix the part that matters.

Performance work without measurement is guesswork. The discipline is: **measure, find the bottleneck, fix it, measure again**.

#### Load testing
Tools like **k6**, Locust, Gatling, JMeter or autocannon simulate many users hitting your API.
- Define a realistic scenario (login, browse, checkout) and targets (for example p95 under 300 ms at 200 requests per second).
- Ramp load up gradually to find the **knee**, where latency starts climbing sharply.
- Run against a production-like environment with realistic data volumes; an empty database lies.
- Watch server metrics during the test to see which resource saturates first: CPU, DB connections, memory or an external API.

#### Profiling
A **profiler** shows where CPU time or memory goes inside your process:
- **CPU profiles** and **flame graphs**: the widest bars are where time is spent. Node has `--cpu-prof` and Clinic.js, Python has cProfile and py-spy, Go has pprof, Java has JFR and async-profiler.
- **Heap snapshots** and allocation profiles find memory leaks: objects that keep growing between snapshots.
- **Continuous profiling** in production (Pyroscope, Parca, cloud profilers) catches issues that only appear under real traffic.

#### The usual suspects
In most backends the bottleneck is not your language but I/O: N+1 queries, missing indexes, chatty calls to other services, large JSON serialization, synchronous CPU work blocking an event loop, or no caching. Fix these before micro-optimizing loops.

#### Pitfalls
- Optimizing code that accounts for 1 percent of the time.
- Load testing from a laptop that becomes the bottleneck itself.

You are ready to move on when you can load test an endpoint, find its bottleneck with a flame graph or query plan, fix it and show the before and after numbers.

Key concepts: Load testing with k6 or Locust, Finding the saturation point, CPU profiles and flame graphs, Heap snapshots and memory leaks, Event loop blocking, Continuous profiling, Benchmarking methodology.

Mini project: Write a k6 script for your three busiest endpoints, find the first bottleneck, fix it using a profile or query plan, and publish a short before/after report with p95 and throughput.

Self-check: Your p95 latency doubles under load while CPU stays at 30 percent. What are the likely bottlenecks?

Resources:
- [Grafana k6 documentation](https://grafana.com/docs/k6/latest/) (Grafana Labs)
- [Flame Graphs](https://www.brendangregg.com/flamegraphs.html) (Brendan Gregg)
- [Profiling Node.js applications](https://nodejs.org/en/learn/getting-started/profiling) (Node.js)

## Building for Scale and Resilience

Design services that grow with traffic and keep working, perhaps partially, when parts of the system fail.

### Vertical and Horizontal Scaling

core · intermediate · about 3 h · https://www.internhack.in/roadmaps/tracks/backend/scaling-strategies

Know when to buy a bigger machine, when to add more machines, and what your code must do to allow the latter.

Scaling means handling more load without falling over or slowing down. There are two basic moves, and most real systems use both.

#### Vertical scaling (scale up)
Give the same server more CPU, memory or faster disks. It is simple, needs no code changes, and modern machines are enormous; a single well-tuned Postgres server handles far more than most startups need. Limits: a ceiling on machine size, cost that rises steeply at the top, and a single point of failure.

#### Horizontal scaling (scale out)
Run more instances behind a load balancer. It gives near-unlimited capacity and redundancy, but requires your app to be **stateless**:
- Sessions in Redis or signed tokens, not process memory.
- Uploads in object storage, not local disk.
- Scheduled jobs that run once across the fleet, not once per instance.
- Caches that are shared or tolerant of inconsistency.

#### Autoscaling
Platforms add and remove instances based on CPU, request rate, queue depth or custom metrics. Set sensible minimums (for redundancy), maximums (for cost and database protection) and cooldowns to avoid flapping.

#### Scaling the rest of the stack
The app tier is usually the easy part. The database, caches and third-party APIs become the next bottlenecks, which is why pooling, replicas, caching and queues exist. Think about each **stateful** component separately.

#### Capacity planning
Know your current peak, your growth rate and the load at which each component saturates (from load tests). Plan headroom (for example handle 2x peak) and revisit it regularly.

#### Pitfalls
- Scaling out an app whose database is the bottleneck, which only makes contention worse.
- Premature distribution: running twenty instances of a service that one machine could handle.

You are ready to move on when your app runs correctly as three instances behind a load balancer, and you can name the next bottleneck and what you would do about it.

Key concepts: Vertical scaling, Horizontal scaling, Stateless application design, Autoscaling policies, Scaling stateful components, Capacity planning.

Mini project: Run your app as three instances behind a load balancer, move all instance-local state to shared services, and prove it by killing instances during a load test with no failed user sessions.

Self-check: List three kinds of state that break when you go from one instance to three, and where each should live instead.

Resources:
- [The System Design Primer](https://github.com/donnemartin/system-design-primer) (GitHub)
- [AWS Well-Architected Framework](https://docs.aws.amazon.com/wellarchitected/latest/framework/welcome.html) (AWS)
- [Autoscaling guidance](https://learn.microsoft.com/en-us/azure/architecture/best-practices/auto-scaling) (Microsoft Learn)

### Timeouts, Retries and Circuit Breakers

core · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/resilience-patterns

Keep a failing dependency from taking your whole service down with timeouts, safe retries, circuit breakers and bulkheads.

Every network call can be slow or fail. In a system with many dependencies, something is always degraded. **Resilience patterns** stop one bad dependency from cascading into a full outage.

#### Timeouts
The most important and most often missing pattern. Without a timeout, a slow dependency ties up your threads or connections until you have none left. Set explicit connect and request timeouts on every HTTP client, database query and queue call, and keep them shorter than the caller's own timeout.

#### Retries, carefully
- Retry only **transient** failures (timeouts, 503, connection resets), never 400-level validation errors.
- Use **exponential backoff with jitter** so thousands of clients do not retry in lockstep.
- Cap attempts, and only retry **idempotent** operations or ones protected by idempotency keys.
- Beware **retry amplification**: three layers each retrying three times turns one failure into 27 calls.

#### Circuit breakers
A **circuit breaker** watches failures to a dependency. After too many, it **opens** and fails fast for a while instead of waiting on timeouts, then goes **half-open** to test with a few requests before closing again. This gives the dependency room to recover and keeps your latency predictable. Libraries: opossum (Node), resilience4j (Java), Polly (.NET), or a service mesh.

#### Bulkheads and fallbacks
- **Bulkheads** isolate resources (separate pools or concurrency limits per dependency) so a slow recommendation service cannot exhaust the pool that checkout needs.
- **Fallbacks** return something useful when a call fails: cached data, a default value, or a reduced feature.

#### Test it
Inject failures on purpose (toxiproxy, chaos experiments) to verify behavior before a real outage does.

You are ready to move on when a dependency in your system can be made slow or dead and your service still responds quickly with a fallback, and you can show the breaker opening in your metrics.

Key concepts: Timeouts everywhere, Retries with backoff and jitter, Retry amplification, Circuit breakers, Bulkheads, Fallbacks, Fault injection and chaos testing.

Mini project: Put toxiproxy between your API and a dependency, add timeouts, jittered retries and a circuit breaker with a cached fallback, and chart latency with the dependency healthy, slow and down.

Self-check: Why can adding retries at every layer of a call chain make an outage worse?

Resources:
- [Timeouts, retries, and backoff with jitter](https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/) (Amazon Builders' Library)
- [CircuitBreaker](https://martinfowler.com/bliki/CircuitBreaker.html) (Martin Fowler)
- [Bulkhead pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/bulkhead) (Microsoft Learn)

### Throttling, Backpressure and Graceful Degradation

recommended · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/load-management

Stay up under overload by shedding, deferring or reducing work instead of collapsing.

Every system has a maximum capacity. What matters is what happens beyond it: a well-designed service slows down gracefully and keeps serving its most important traffic; a poorly designed one falls over completely and takes a long time to recover.

#### Throttling and rate limiting
Limit how much work each client or tenant may send (token bucket, sliding window), returning `429 Too Many Requests` with `Retry-After`. Per-tenant limits stop one noisy customer from degrading everyone else.

#### Load shedding
When the server itself is overloaded, reject some requests early and cheaply (for example a `503`) rather than accepting everything and timing out on all of it. Shed **low-priority** traffic first: background syncs and analytics before checkout and login. Bounded queues with a max wait time are a simple form of this.

#### Backpressure
Producers must slow down when consumers cannot keep up. Examples: bounded in-memory queues, stream `highWaterMark` in Node, consumer prefetch limits in brokers, and HTTP clients honoring 429s. Unbounded buffers only turn overload into out-of-memory crashes.

#### Load shifting and leveling
Move non-urgent work out of the peak: put it on a **queue** and let workers process at a steady rate, precompute results off-peak, and schedule batch jobs at night. The queue absorbs spikes that would otherwise hit the database.

#### Graceful degradation
Decide ahead of time which features can switch off: hide recommendations, serve cached or slightly stale data, disable expensive search filters, or show a read-only mode. **Feature flags** make these switches fast during an incident.

#### Recovery
After an outage, a backlog of retries can knock the system down again (a **thundering herd**). Jittered retries, limits on queue drain rate and warm-up of caches prevent a second collapse.

You are ready to move on when you can overload your service in a test and show it keeps serving priority endpoints while shedding the rest.

Key concepts: Per-client and per-tenant throttling, Load shedding and priorities, Backpressure, Queue-based load leveling, Graceful degradation with feature flags, Thundering herd on recovery.

Mini project: Add per-tenant rate limits and a priority-aware load shedder to your API, then run a load test above capacity and show login and checkout stay healthy while low-priority endpoints return 503.

Self-check: What is the difference between rate limiting a client and load shedding on the server, and when do you need each?

Resources:
- [SRE Book: Handling Overload](https://sre.google/sre-book/handling-overload/) (Google)
- [SRE Book: Addressing Cascading Failures](https://sre.google/sre-book/addressing-cascading-failures/) (Google)
- [Queue-Based Load Leveling pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/queue-based-load-leveling) (Microsoft Learn)

### Zero-Downtime Deploys and Migrations

core · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/zero-downtime-changes

Ship code and schema changes to a live system without outages using rolling, blue-green and expand-contract techniques.

At scale, "we will take the site down for maintenance on Sunday" stops being acceptable. Every deploy and schema change must happen while traffic flows.

#### Deployment strategies
- **Rolling**: replace instances a few at a time. Old and new versions run side by side briefly, so they must be compatible.
- **Blue-green**: run the new version as a full parallel environment and switch traffic at once, with instant rollback by switching back.
- **Canary**: send a small percentage of traffic to the new version, watch error and latency metrics, then expand or roll back automatically.
All rely on health checks, graceful shutdown (drain in-flight requests on SIGTERM) and good metrics.

#### Expand and contract for schemas
Because two app versions overlap, never make a breaking schema change in one step. Renaming a column, for example:
1. **Expand**: add the new column; deploy code that writes to both.
2. **Migrate**: backfill existing rows in batches.
3. Switch reads to the new column.
4. **Contract**: stop writing the old column, then drop it in a later release.

#### Safe migration habits
- Know which DDL takes heavy locks. Adding a column with a volatile default, adding a non-concurrent index or changing a type can block writes on large tables. Use `CREATE INDEX CONCURRENTLY`, add constraints as `NOT VALID` then validate, and set a `lock_timeout`.
- Backfill in small batches with pauses, never one giant `UPDATE`.
- Make every migration reversible or have a documented forward fix.

#### Feature flags
Deploying code is not the same as releasing a feature. Ship code dark behind a **feature flag**, enable it for staff, then a percentage of users. Remove flags once rolled out.

You are ready to move on when you can rename a column on a table under constant load with no errors, using expand and contract across multiple deploys.

Key concepts: Rolling deployments, Blue-green deployments, Canary releases, Expand and contract migrations, Lock-safe DDL, Batched backfills, Feature flags.

Mini project: While a load test runs against your API, rename a column using expand and contract over three deploys and show zero failed requests in your metrics.

Self-check: Why can you not drop an old column in the same deploy that stops using it during a rolling deployment?

Resources:
- [ParallelChange (expand and contract)](https://martinfowler.com/bliki/ParallelChange.html) (Martin Fowler)
- [BlueGreenDeployment](https://martinfowler.com/bliki/BlueGreenDeployment.html) (Martin Fowler)
- [Feature Toggles](https://martinfowler.com/articles/feature-toggles.html) (Martin Fowler)

## Putting It All Together

Review designs like a senior engineer and ship one production-grade backend that proves your skills.

### API and System Design Reviews

recommended · advanced · about 4 h · https://www.internhack.in/roadmaps/tracks/backend/api-design-review

Evaluate an API or system design against a checklist of correctness, security, scale and operability before it ships.

Much of senior backend work is not writing code but **reviewing designs**: catching the missing index, the unauthenticated endpoint or the breaking change before it reaches production. It is also exactly what system design interviews test.

#### Write the design down first
A short design doc (context, goals and non-goals, API sketch, data model, alternatives considered, rollout plan) lets reviewers find problems while they are cheap to fix. Many teams use a lightweight **RFC** or **ADR** (architecture decision record) format.

#### A review checklist
- **Contract**: consistent naming, correct methods and status codes, one error format, pagination on every list, idempotency for retried writes, a versioning and deprecation plan. Compare against a public style guide such as Google's AIPs or Zalando's guidelines.
- **Security**: authentication on every route, object-level authorization checks, input validation, rate limits, no secrets or personal data in logs.
- **Data**: schema fits the access patterns, indexes for each query, migrations are backwards compatible, transactions where invariants span rows.
- **Scale**: expected traffic and data growth, caching strategy, what happens at 10x load, which component saturates first.
- **Failure**: timeouts, retries, fallbacks, what the user sees when each dependency is down.
- **Operability**: logs, metrics, traces and alerts; a runbook; a rollback plan.

#### Estimation
Do back-of-the-envelope math: requests per second at peak, storage per year, bandwidth. Order-of-magnitude answers are enough to spot designs that cannot work.

#### Giving feedback
Separate blocking issues from suggestions, explain the risk behind each comment, and propose an alternative rather than only saying no.

You are ready to move on when you can review a design doc for a feature like "shareable file links" and produce a prioritized list of risks with concrete fixes.

Key concepts: Design docs, RFCs and ADRs, API contract checklist, Security review, Data model and index review, Failure mode analysis, Back-of-the-envelope estimation, Public API style guides, Giving constructive review feedback.

Mini project: Write a two-page design doc for a URL shortener with analytics, then review it yourself against the checklist and revise it, keeping the list of issues you found and fixed.

Self-check: Name five questions you would ask in a review of a new public endpoint that lists a user's invoices.

Resources:
- [Google API Improvement Proposals](https://google.aip.dev/) (Google)
- [Zalando RESTful API Guidelines](https://opensource.zalando.com/restful-api-guidelines/) (Zalando)
- [Architecture decision records](https://adr.github.io/) (adr.github.io)

### Capstone: Ship a Production-Grade Backend

core · advanced · about 40 h · https://www.internhack.in/roadmaps/tracks/backend/capstone-project

Build, deploy and operate one complete backend service that brings together everything on this roadmap.

Reading about backends is not the same as running one. This capstone is the portfolio piece that shows an interviewer you can design, build, ship and operate a real service. Pick a domain you care about: a booking system, a team task tracker, a mini e-commerce store, a job board.

#### Required features
- A documented **REST or GraphQL API** with an OpenAPI or schema file, consistent errors, pagination and validation.
- **Authentication** (sessions or JWT, plus one OAuth login) and **role-based authorization** with object-level checks.
- A **relational database** with migrations, indexes that match your queries and at least one multi-step transaction.
- **Caching** of one hot read path with an invalidation strategy.
- **Background jobs** for email or file processing, with retries and a dead-letter view.
- One **real-time** feature (notifications over SSE or WebSockets) or **file uploads** to object storage.

#### Engineering quality
- Unit and integration tests running in **CI**, with the pipeline building a **Docker** image and deploying automatically.
- Configuration through environment variables, secrets never in the repo.
- Structured logs with request ids, RED metrics, and a health endpoint.
- Security basics: hashed passwords, rate-limited login, security headers, dependency scanning.

#### Prove it works
- A **load test** report with p95 latency at a target throughput and the bottleneck you fixed.
- A short **README** with an architecture diagram, setup steps and trade-offs you made.
- A **runbook** entry: what you would check if error rates spiked.

#### Stretch goals
Split one component into a separate service over a queue, add tracing with OpenTelemetry, or run it on Kubernetes.

You are done when a stranger can clone the repo, run it with one command, read your design decisions and hit a live deployed URL, and you can explain every choice in an interview.

Key concepts: Choose a domain and write a design doc, Documented API with auth and RBAC, Database with migrations and indexes, Caching and background jobs, Tests and CI/CD to a live URL, Logs, metrics and health checks, Load test and performance report, README, diagram and runbook, Stretch: service split, tracing or Kubernetes.

Mini project: Build and deploy the capstone service described here, publish the repository with its README, design doc and load test report, and share the live URL.

Self-check: Could you walk an interviewer through your capstone's request path from DNS lookup to database row, naming every component and why it is there?

Resources:
- [The Twelve-Factor App](https://12factor.net/) (12factor.net)
- [The System Design Primer](https://github.com/donnemartin/system-design-primer) (GitHub)
- [Build your own X](https://github.com/codecrafters-io/build-your-own-x) (GitHub)

## Related

- [Career roadmaps](https://www.internhack.in/roadmaps)
