Backend Engineering, learned from your own code
90 lessons built from five real projects: Spring-Boot-Store, Hostel-Web-App, Report-Manager-2, IR3D and SperoTek. Every concept shows a detailed example, where you used it, how you used it, why it was chosen, the alternatives, and the related ideas you need to know.
Start lesson 1 →See the project inventory
The projects, from simplest to most advanced
Spring-Boot-Store
E-commerce API: package-by-layer, JPA relationships, JWT, Stripe checkout.
Hostel-Web-App
Hostel booking: package-by-feature, PostGIS, locking, STOMP, AWS CDK/Fargate.
Report-Manager-2
Financial reporting: modular monolith, RabbitMQ, SSE, caching, AOP auditing.
IR3D (Kontentt)
Creator platform: wallet ledger, Paystack, S3/CloudFront, chat, passkeys, AWS.
SperoTek (in dev)
Accounting SaaS: Spring Modulith, multi-tenancy, DB triggers, SSO, outbox.
1. Foundations
HTTP, Spring Boot, dependency injection, project structure and configuration.
- 1.1HTTP & REST fundamentalsEvery backend you have built speaks HTTP. Learn methods, status codes, headers, statelessness and what actually makes an API "RESTful".
- 1.2Spring Boot, IoC & Dependency InjectionWhat Spring actually does when your app starts. The container, beans, constructor injection, auto-configuration and starters.
- 1.3Project structure, from layers to modulesYour projects show the full evolution. Package-by-layer, then package-by-feature, then a modular monolith, then Spring Modulith with enforced boundaries.
- 1.4Configuration, profiles & environment variablesapplication.yaml, profiles, env-var placeholders, .env files, typed @ConfigurationProperties and failing fast on unsafe production config.
- 1.5Modern Java for backend work (records, Lombok, Java 25)Records, sealed types, switch expressions, unnamed variables, Lombok and when to use each. All your projects run Java 25.
- 1.6Aspect-Oriented Programming (AOP) & custom annotationsHow @Audited, @RequirePermission and @RequireStepUpMfa work. Pointcuts, advice, proxies, and when AOP is the right tool.
2. API Design
Controllers, DTOs, validation, errors, pagination, filtering and documentation.
- 2.1Controllers & DTOs, and why entities never leave the serviceThe request lifecycle in Spring MVC, @RestController mechanics, and why every project uses separate request/response DTOs instead of exposing entities.
- 2.2Object mapping with MapStructCompile-time generated mappers. @Mapping, expressions, @MappingTarget for updates, and how it compares to manual mapping and ModelMapper.
- 2.3Input validation & custom validatorsBean Validation (Jakarta), @Valid, groups, writing your own constraint like @StrongPassword or @SafeText, and the layers of validation a real system needs.
- 2.4Global error handling, error codes & response envelopes@RestControllerAdvice, a consistent ApiError shape, machine-readable error codes, correlation ids, i18n messages, and whether to wrap successes in an envelope.
- 2.5Pagination & sorting, offset vs cursorSpring Data Pageable, @PageableDefault, sort whitelisting, PageResponse DTOs, and when to switch to keyset (cursor) pagination.
- 2.6Dynamic filtering with JPA SpecificationsComposable WHERE clauses with the Criteria API. HostelSpecifications.filterHostels, ReportSubmissionSpecs.isAccessibleBy, and the alternatives (Querydsl, jOOQ, derived queries).
- 2.7API documentation (OpenAPI) & versioningspringdoc-openapi and Swagger UI, documenting security, versioning strategies (/api/v1 vs headers), and evolving APIs without breaking clients.
3. Databases (Deep Dive)
Modeling, constraints, migrations, JPA, indexes, transactions, locking and PostGIS.
- 3.1Relational modeling & primary keys (UUID v4 vs v7)Tables, rows, keys, relationships and cardinality. Surrogate vs natural keys, and why SperoTek uses UUIDv7 while the others use random UUIDs.
- 3.2Normalization & deliberate denormalization1NF, 2NF, 3NF and BCNF explained with your schemas, and the times you rightly broke the rules (order snapshots, cached occupancy, GIN tag arrays).
- 3.3Constraints, the database as the last line of defenceNOT NULL, CHECK, UNIQUE, partial unique, deferrable, foreign keys with ON DELETE actions, and SperoTek's composite tenant foreign keys.
- 3.4Schema migrations with Liquibase (and ddl-auto validate)Versioned, repeatable schema changes. Changelogs, changesets, raw-SQL includes, seed data, rollbacks, and why every project sets ddl-auto to validate.
- 3.5JPA entities & relationships, including cascade, orphanRemoval and owning sidesHow Hibernate maps objects to tables. @ManyToOne, @OneToMany(mappedBy), @ManyToMany, @MapsId, cascade types, orphanRemoval, the persistence context, and why SperoTek mostly avoids associations.
- 3.6Lazy loading, the N+1 problem, @EntityGraph & JOIN FETCHThe most common JPA performance bug. How to spot it in SQL logs and fix it with fetch joins, entity graphs, batch fetching or projections.
- 3.7Querying, from derived queries to JPQL, native SQL, CTEs, projections and JdbcClientEvery way your projects read data, when each is the right tool, plus SQL concepts (joins, aggregates, CTEs, window functions) you must be fluent in.
- 3.8Indexes, including B-tree, composite, partial, GIST and GINHow indexes work internally, the leftmost-prefix rule, partial and expression indexes, spatial GIST and array GIN indexes from Hostel, and the cost every index adds to writes.
- 3.9Transactions, ACID & isolation levelsWhat a transaction really guarantees. Atomicity through durability, MVCC in Postgres, the read anomalies (dirty, non-repeatable, phantom, lost update, write skew) and which isolation level prevents each.
- 3.10@Transactional in depth: propagation, readOnly, rollback rules & trapsHow Spring's transaction proxy works, REQUIRED vs REQUIRES_NEW vs MANDATORY, readOnly optimizations, checked-exception rollback, self-invocation, and controller-level transactions.
- 3.11Concurrency control with optimistic, pessimistic & advisory locks@Version optimistic locking, SELECT ... FOR UPDATE pessimistic locking, Postgres advisory locks for gap-free numbering, and how to choose.
- 3.12Soft delete, triggers & append-only tablesis_deleted vs real deletes, retention purges, PL/pgSQL triggers that make posted journals immutable, and append-only audit logs that even a DBA cannot edit by accident.
- 3.13Money & time, the two data types that break systemsWhy money is NUMERIC/BigDecimal (never double), minor units for payment APIs, rounding, and why every project stores UTC while showing Africa/Accra.
- 3.14Connection pooling (HikariCP) & open-in-viewWhy connections are pooled, how to size the pool, what happens when it runs out, and why every one of your projects sets spring.jpa.open-in-view to false.
- 3.15Geospatial data with PostGISStoring locations as geometry Points, SRID 4326, geometry vs geography, ST_Distance and ST_DWithin, GIST indexes, and Hibernate Spatial/JTS mapping, all from Hostel's map feature.
4. Security
Hashing, JWT, refresh tokens, cookies, CSRF/CORS, OAuth, MFA, passkeys and more.
- 4.1Password storage with BCrypt, Argon2 & breach checksWhy hashing (not encryption), salts, work factors, BCrypt cost 10 vs 12, Argon2id memory hardness, password policies, history, lockout and Have-I-Been-Pwned checks.
- 4.2Sessions vs JWT, and how JWTs actually workServer sessions vs stateless tokens, JWT structure, HS256/HS512 vs RS256, the claims you need, the authentication filter, and the revocation problem SperoTek solved with server-side sessions.
- 4.3Signing-key rotation with kid & key ringsHow to change a JWT or encryption key without logging everyone out. The kid header, active vs verification keys, and the same key-ring idea for AES-GCM secrets.
- 4.4Refresh tokens, rotation, reuse detection & session managementShort access plus long refresh tokens, storing only hashes, rotation on every use, detecting stolen tokens via reuse, per-user session caps, device lists and "sign out other devices". Five projects show five maturity levels.
- 4.5Cookies, CORS & CSRF, the browser security trioHttpOnly/Secure/SameSite/Domain cookie attributes, what CORS really protects (and doesn't), preflight requests, CSRF attacks, and why "CSRF disabled + JWT in a cookie" is a trap.
- 4.6Authorization with roles, permissions, ownership & method securityAuthentication vs authorization, URL rules vs @PreAuthorize, RBAC vs permission-based access, custom annotations, object-level (ownership) checks and the IDOR bugs they prevent.
- 4.7OAuth 2.0 & OpenID Connect, including Google, Apple and social linkingOAuth vs OIDC, the authorization-code flow with PKCE, ID tokens vs access tokens, verifying Google and Apple ID tokens, account linking, and storing third-party tokens safely.
- 4.8Enterprise SSO with SAML 2.0, OIDC for companies & domain verificationHow B2B SaaS lets companies log in with their own identity provider (Okta, Entra ID). SAML assertions, SP vs IdP, ACS endpoints, per-tenant relying parties and DNS TXT domain proof.
- 4.9MFA, covering TOTP, email codes, recovery codes, step-up & passkeys (WebAuthn)How TOTP works (RFC 6238), encrypting TOTP secrets, recovery codes, trusted devices, step-up authentication for sensitive actions, and phishing-resistant passkeys.
- 4.10One-time tokens for email verification, password reset & invitationsGenerating unguessable tokens with SecureRandom, hashing them at rest, single use and short expiry, anti-enumeration responses, and invalidating sessions after a reset.
- 4.11Rate limiting with sliding windows, token buckets & Bucket4jFixed window, sliding window and token bucket algorithms, per-IP vs per-user keys, 429 + Retry-After, the X-Forwarded-For spoofing trap, and moving from in-memory to Redis when you scale.
- 4.12Security headers & input attacks (XSS, SQLi, SSRF)CSP, HSTS, X-Frame-Options, Referrer-Policy, Permissions-Policy, plus how XSS, SQL injection and SSRF work and how IR3D's SafeHttpFetcher blocks requests to internal networks.
- 4.13Encryption at rest with AES-GCM in your applicationSymmetric encryption fundamentals, why AES-GCM (authenticated), nonces/IVs, ciphertext format with key id, what to encrypt vs hash, and disk/DB encryption layers.
- 4.14Verifying webhooks with HMAC signatures (Stripe & Paystack)How providers sign webhook payloads, why you need the raw body, constant-time comparison, replay protection with timestamps and event ids, and idempotent processing.
- 4.15Secrets management, and what to do when one leaksWhere secrets should live, .gitignore and pre-commit scanning, SSM and Secrets Manager, least-privilege IAM, and a step-by-step leaked-secret response using real findings from your repos.
5. Async & Integrations
Thread pools, schedulers, events, outbox, RabbitMQ, real-time, storage and payments.
- 5.1@Async & thread pools: background work inside the appWhy slow work (email, push, exports) shouldn't run on the request thread, ThreadPoolTaskExecutor sizing (core, max, queue), rejection policies, named executors and losing work on restart.
- 5.2Scheduled jobs with cron, fixedDelay, sweepers & job observability@Scheduled cron vs fixedRate vs fixedDelay, zone-aware cron, writing robust sweepers (batching, per-item error handling), recording job runs, and the multi-instance problem (ShedLock).
- 5.3Domain events & @TransactionalEventListenerDecoupling with ApplicationEventPublisher, synchronous vs after-commit listeners, transaction phases, why you notify only after commit, and Spring Modulith's @ApplicationModuleListener.
- 5.4The transactional outbox patternThe dual-write problem, writing events to an outbox table inside the same transaction, relaying them, at-least-once delivery, and how Spring Modulith's event_publication table plus SperoTek's sealed email outbox implement it.
- 5.5RabbitMQ, covering exchanges, queues, DLQs, retries & resilienceAMQP model (producer → exchange → binding → queue → consumer), exchange types, durability, acks, retry with backoff, dead-letter exchanges, poison messages, and RM's broker-down fallback.
- 5.6Transactional email with SMTP, SES, Thymeleaf templates & deliverabilityJavaMailSender, HTML + text templates with Thymeleaf, Gmail vs Amazon SES, SPF/DKIM/DMARC, staging safety, Mailpit for local testing and bounce handling.
- 5.7Real-time with polling, SSE, WebSockets/STOMP & Web PushChoosing between polling, Server-Sent Events and WebSockets, STOMP destinations and user queues, authenticating CONNECT frames, heartbeats, presence, VAPID/FCM/Expo push, and why in-memory brokers do not scale out.
- 5.8File storage, covering DB blobs, Cloudinary signed uploads, S3 + CloudFrontWhere files should live, direct-to-storage uploads with signatures, presigned URLs, CDNs and signed cookies for private media, transcoding, and migrating providers safely.
- 5.9Payments with Stripe Checkout, Paystack, manual references & compensationHosted checkout vs custom forms, the order/payment state machine, metadata to link payments to orders, webhooks as the source of truth, compensation on failure, payouts and reconciliation.
- 5.10Ports & adapters, the Strategy pattern & pluggable providersHiding third parties behind interfaces, swapping implementations with config, stub adapters for dev and tests, and the Strategy pattern behind RM's report generators.
- 5.11Generating Excel, PDF & CSV, plus async export jobsApache POI vs fastexcel, OpenPDF, CSV pitfalls (formula injection, encoding), streaming large files, and the 202-Accepted async export job pattern.
6. Domain-Heavy Design
Ledgers, state machines, approvals, multi-tenancy, auditing and idempotency.
- 6.1Double-entry ledgers for money you can trustDebits and credits, journal entries and lines, the balance invariant, chart of accounts, account types, gap-free numbering, reversals not edits, open periods, and wallets built on a ledger.
- 6.2State machines for bookings, journals & reportsModeling lifecycles explicitly, allowed transitions, guarding them in code and DB, action endpoints, side effects per transition, and what to do with time-based transitions.
- 6.3Approval workflows with policies, delegation, escalation & maker-checkerSegregation of duties, who approves what, approval policies by amount or type, delegation while away, scheduled escalation, and hierarchical (unit-tree) approvers.
- 6.4Multi-tenancy, from discriminator column to schema or DB per tenantThe three tenancy models and their trade-offs, Hibernate @TenantId, resolving the tenant from the URL, ThreadLocal context, composite FKs, tenant-isolation tests and Postgres Row-Level Security.
- 6.5Audit logs & activity trailsWhat to record (who, what, when, where, before and after, why), audit vs activity vs application logs, capturing changes with AOP or explicit recorders, retention, immutability and compliance reports.
- 6.6Idempotency keys & exactly-once effectsMaking POST safe to retry with Idempotency-Key headers, unique constraints as the guard, storing responses, idempotent consumers for webhooks and queues, and natural idempotency.
7. Testing
Unit tests, slices, Testcontainers, async assertions and architecture tests.
- 7.1The testing pyramid, unit tests & MockitoUnit vs slice vs integration vs end-to-end tests, writing fast unit tests with JUnit 5 and Mockito, what to mock (and what not to), fixtures and naming.
- 7.2Slice tests with @WebMvcTest & security testsTesting controllers without the whole app. MockMvc, @MockitoBean, testing 401/403/400 paths, method-security config in tests, and why Hostel's rate-limit filter is not a @Component.
- 7.3Integration tests with Testcontainers & @ServiceConnectionReal PostgreSQL (and RabbitMQ, Mailpit) in Docker for tests, the singleton-container pattern, abstract base classes, running all migrations, and why H2 is not a substitute.
- 7.4Testing async code, architecture rules & coverageAwaitility for eventual outcomes, testing events and outboxes, Spring Modulith verify, ArchUnit rules, JaCoCo coverage and what coverage does not tell you.
8. DevOps & Production
Docker, CI/CD, infrastructure as code, deployment and observability.
- 8.1Docker for Java with multi-stage builds, non-root users, distroless & JVM memoryImages vs containers, layer caching, multi-stage builds, layered jars, non-root and distroless runtimes, healthchecks, and container-aware JVM flags (MaxRAMPercentage, ExitOnOutOfMemoryError).
- 8.2docker-compose for local dev with healthchecks, watch, profiles & toolingOne command to run the whole stack. depends_on with healthchecks, compose watch for hot rebuild, debug ports, optional tools via profiles, init scripts, and spring-boot-docker-compose.
- 8.3CI/CD with GitHub Actions, path filters, OIDC to AWS & image taggingContinuous integration vs delivery vs deployment, workflow anatomy, path filters for monorepos, keyless AWS auth with OIDC, tagging images by git SHA, and deploy strategies.
- 8.4Infrastructure as code & deployment targets (CDK, CloudFormation, Fargate, EC2, Cloudflare Tunnel)Why IaC, CDK vs CloudFormation vs Terraform, VPCs and private subnets, ALB + Fargate, RDS with generated secrets, EC2 + SSM, and exposing apps through Cloudflare Tunnel with no inbound ports.
- 8.5Observability with logs, correlation IDs, metrics, health & error trackingThe three pillars (logs, metrics, traces), structured logging, MDC correlation ids, Actuator health, liveness and readiness probes, Prometheus + Grafana, SLOs, and Sentry with PII scrubbing.
- 8.6Graceful shutdown & the limits of one instanceGraceful shutdown, statelessness, and every piece of in-memory state in your projects that breaks when you run two instances (schedulers, rate limits, WebSocket brokers, SSE, caches), with the fix for each.
9. Bonus: Beyond Your Projects
What every backend engineer must know that your projects have not used yet.
- 9.1Caching & Redis strategies, invalidation and stampedesCache-aside, read-through, write-through and write-behind, TTLs, invalidation, the thundering herd, Spring Cache with Redis, and the other things Redis does (rate limits, locks, pub/sub, sessions).
- 9.2Distributed systems fundamentals, covering CAP, consistency, consensus & failureThe fallacies of distributed computing, CAP and PACELC, consistency models, replication and quorums, consensus (Raft), clocks and ordering, and partial failure.
- 9.3Distributed transactions, from 2PC to sagas (orchestration vs choreography)Why ACID stops at the service boundary, two-phase commit and its problems, the saga pattern with compensating actions, orchestration vs choreography, and workflow engines like Temporal.
- 9.4Kafka, event sourcing & CQRSKafka's log model (topics, partitions, offsets, consumer groups, retention), when to pick it over RabbitMQ, event sourcing (state as a fold over events), and CQRS read models.
- 9.5Microservices vs the modular monolith, plus gateways, discovery & service meshWhen splitting into services is worth it, database-per-service, API gateways, service discovery, inter-service auth, the strangler-fig migration, and why your Modulith is the right starting point.
- 9.6GraphQL & gRPC, the other API stylesGraphQL schemas, resolvers, the N+1 problem and DataLoader, field-level auth and query cost limits; gRPC with Protobuf, HTTP/2 streaming and when each beats REST.
- 9.7Scaling data with replication, partitioning, sharding & load balancingLoad balancer algorithms, read replicas and replication lag, Postgres declarative partitioning, sharding strategies and their pain, and the order in which to reach for each.
- 9.8Reading query plans with EXPLAIN ANALYZE & Postgres performance tuningHow the planner works, scan and join types, reading EXPLAIN (ANALYZE, BUFFERS), statistics and ANALYZE, pg_stat_statements, VACUUM and bloat, and a tuning checklist.
- 9.9NoSQL & search engines (MongoDB, Cassandra, DynamoDB, Elasticsearch)Document, key-value, wide-column and graph stores, when each beats Postgres, modeling for access patterns, and full-text search with Postgres tsvector vs Elasticsearch/OpenSearch.
- 9.10Kubernetes essentials for backend engineersPods, Deployments, Services, Ingress, ConfigMaps and Secrets, probes, resource requests and limits, HPA autoscaling, rolling updates, and how your Docker and Actuator setup maps onto it.
- 9.11Resilience patterns (timeouts, retries, circuit breakers, bulkheads, fallbacks)Protecting your app from slow or failing dependencies with Resilience4j. Timeouts, retry with backoff and jitter, circuit breaker states, bulkheads, rate limiters and graceful degradation.
- 9.12Java concurrency, covering threads, the memory model, CompletableFuture & virtual threadsRace conditions, visibility and happens-before, synchronized vs locks vs atomics, concurrent collections, CompletableFuture composition, virtual threads, structured concurrency and pinning.
- 9.13OWASP Top 10 (web + API), mapped to your projectsA review checklist. Each OWASP Top 10 and API Security Top 10 risk, where your projects defend against it, and where the analysis found gaps.
- 9.14The system design interview method (with a worked example)A repeatable framework (requirements, estimates, API, data model, high-level design, deep dives, trade-offs), back-of-the-envelope numbers, and a full walk-through designing a hostel booking platform at national scale.
- 9.15Data structures & algorithms in real backendsBig-O for backend work, and where hash maps, trees, heaps, queues, graphs, tries, Bloom filters and consistent hashing actually show up, including inside your own projects.
- 9.16SOLID, clean code & Domain-Driven DesignThe five SOLID principles with examples from your code, DDD strategic design (bounded contexts, ubiquitous language) and tactical design (aggregates, value objects, domain events, repositories).
- 9.17The Twelve-Factor App & feature flagsThe twelve factors as a checklist for cloud-ready services, and feature flags (release, ops, experiment and permission flags) for decoupling deploy from release.
- 9.18Zero-downtime database migrations (expand/contract)Why rolling deploys mean two app versions share one schema, the expand/contract pattern for renames and type changes, backfills in batches, lock-safe DDL in Postgres, and concurrent index builds.
- 9.19Performance & load testing (k6, Gatling, profiling)Load vs stress vs soak vs spike tests, writing a k6 script with thresholds, percentiles over averages, finding bottlenecks with JFR and async-profiler, and capacity planning.
- 9.20Reactive programming with WebFlux, and when it's worth itNon-blocking I/O, Reactor Mono and Flux, backpressure, WebClient, R2DBC, the costs (debugging, ecosystem), and why virtual threads changed the calculus.