Skip to content
devops.academy

Exercises — Module 12: Databases in Operations & GitOps

Part A–D: databases (Compose Postgres locally; RDS free-tier for the managed labs — teardown discipline applies). Part E–G: GitOps on your kind cluster. This module's exercises intentionally reuse YOUR app and YOUR repos — by the end, your whole portfolio runs GitOps-style with operable data.


DATABASES

Part A — Warm-Up Drills

Drill 1 — psql survival reps. In your Compose Postgres: \l, \c appdb, \dt, create a table, insert 5 rows, count them, \d tablename (describe), SELECT * FROM pg_stat_activity; and identify YOUR OWN connection in it. ✓ psql meta-commands are muscle memory; pg_stat_activity is a known place, not a mystery.

Drill 2 — Size awareness. Queries for: database size (pg_size_pretty(pg_database_size(...))), each table's size, row counts. Insert 100k junk rows (generate_series) and re-measure. ✓ You can answer "how big is it and what's growing?" in three queries.

Drill 3 — Dump/restore micro-rep (do 5 times until boring). pg_dump -Fc appdb > d.dump → createdb scratch → pg_restore -d scratch d.dump → verify a row count matches → dropdb scratch. Time yourself. ✓ Under 2 minutes. Restores must be BORING before they're needed at 3 AM.

Drill 4 — Connection census. Open 3 psql sessions; from a 4th, list them via pg_stat_activity with state; terminate one with pg_terminate_backend(pid); check SHOW max_connections;. ✓ You can see, count, and kill connections on demand.


Part B — Guided Labs (Databases)

Lab 1 — Backups You'd Bet a Job On (2 h)

  1. Script (bash or Python — your choice, both exist now): nightly pg_dump -Fc → timestamped file → upload to S3 (versioned bucket) → prune local older than 7 days → log everything.
  2. The drill that matters: restore LAST NIGHT's S3 backup to a fresh container, run a verification query set (row counts of 2 tables + one known record). Script THAT too — restore_verify.sh.
  3. Record your RTO (time from "go" to verified). Write your RPO given a nightly schedule. Now answer: what schedule would an RPO of 1 hour require, and what technique gets you to minutes (name PITR/WAL)?
  4. Monitoring the absence (Module 10 marriage): the backup script pushes a success timestamp metric (node_exporter textfile collector or a Pushgateway/heartbeat file promtail picks up); alert if no success in 26h. Test by disabling the cron. ✓ You have: automated backup, TESTED restore, measured RTO/RPO, and an alert on silent failure. That's the whole checklist, real.

Lab 2 — "Too Many Connections": the Rite of Passage (90 min)

  1. Set max_connections=25 on your Compose Postgres (command flag). Write a Python leak-loop opening connections without closing.
  2. Run it while your app serves traffic → capture the exact FATAL: too many connections in app logs. You've now SEEN the classic.
  3. Diagnose live: pg_stat_activity grouped by state — spot the idle pile.
  4. Fix tier 1: app-side pool (SQLAlchemy pool_size or psycopg pool) sized deliberately; do the arithmetic for "how many app replicas can I run?" and write it down.
  5. Fix tier 2: add PgBouncer to Compose between app and DB (transaction pooling); rerun the leak test THROUGH pgbouncer and observe the difference; check SHOW POOLS; on pgbouncer's admin console. ✓ The incident, the diagnosis query, the arithmetic, and both fixes — experienced, not read.

Lab 3 — Migrations Meet the Pipeline (2 h)

  1. Add a migration tool to your app repo (Alembic for Python / Flyway generic): baseline migration for your existing table; run it; inspect the version-tracking table it created.
  2. Wire migrate as a pipeline step (Module 6) before the deploy step; ship a migration adding a column via a PR end-to-end.
  3. Expand/contract drill — the whole point: rename a column the WRONG way first, locally with two app versions running (old container + new container against one DB) — watch the old one throw column-does-not-exist. Then do it RIGHT across staged changes: add new column + dual-write → backfill script → read-switch → (later) drop. Keep both experiments' notes.
  4. CREATE INDEX vs CONCURRENTLY: on your 100k-row table, run a long write loop while creating an index each way; observe blocking vs not (check pg_stat_activity wait events). ✓ You can explain zero-downtime schema change with YOUR terminal output as evidence.

Lab 4 — RDS + Replication (90 min, teardown after!)

  1. Smallest RDS Postgres, Multi-AZ OFF first; connect from an EC2/your app (SG chain!). Enable automated backups; find the PITR restore-to-time UI and restore to 10 minutes ago into a new instance; verify.
  2. Add a read replica; write to primary, read from replica; measure ReplicaLag in CloudWatch while running an insert loop.
  3. Convert to Multi-AZ; then Reboot with failover while your app runs a query loop — time the outage window and note the DNS-based recovery (connection strings unchanged!).
  4. Prove "replication ≠ backup": drop a table on the primary; watch it vanish from the replica ~instantly; recover it via PITR instead. ✓ Four core managed-DB operations performed, timed, and the replication-vs-backup lesson made visceral. TEARDOWN NOW.

Lab 5 — Redis Ops Quickies (45 min)

  1. redis-cli: INFO memory, set maxmemory 10mb + allkeys-lru; write until eviction; watch evicted_keys climb.
  2. The KEYS footgun: load 100k keys, time KEYS * vs a full SCAN loop; imagine the first one on a prod box serving traffic.
  3. Persistence: with RDB defaults, write keys, docker kill (not stop), restart — what survived? Enable AOF, repeat. ✓ Three one-line rules written: eviction policy always, never KEYS in prod, persistence per use-case.

GITOPS

Part C — Warm-Up Drills (GitOps)

Drill 1 — Install & orient. ArgoCD on kind (module B3 commands); log into the UI; tour: Applications view, Settings→Repositories. Change the admin password. Drill 2 — First app, someone else's. Point an Application at a public example repo (argoproj/argocd-example-apps, guestbook). Sync manually; explore the resource tree view — click into the live Deployment, see the diff tab. ✓ You can navigate app → resource tree → live manifest → events without the CLI. Drill 3 — CLI parity. Install argocd CLI; login; argocd app list, app get, app sync, app history. Every UI action, once via CLI.


Part D — Guided Labs (GitOps)

Lab 1 — Two-Repo Split (90 min)

  1. Create myapp-config repo: apps/api/base/ (your K8s manifests or Helm chart) + overlays/staging/ and overlays/prod/ (Kustomize patches: replicas, host, tag).
  2. kustomize build overlays/staging locally — read the output diff vs prod before ArgoCD ever touches it.
  3. Two ArgoCD Applications: staging (automated sync + selfHeal + prune) and prod (manual sync). Both green. ✓ One base, two envs, desired state entirely in Git.

Lab 2 — The selfHeal "Aha" + Prune (30 min)

  1. kubectl scale deploy api -n staging --replicas=10 by hand. Watch the app flash OutOfSync and snap back to Git's count within seconds. Do it twice; the second time, watch the ArgoCD app events explain it.
  2. Delete a resource from Git (e.g., remove the HPA from the overlay), commit — watch prune remove it from the cluster.
  3. In PROD (manual sync): make the same hand-edit — observe it shows OutOfSync but does NOT revert. Discuss with yourself which behavior belongs in which env and why teams often differ. ✓ Drift correction and prune witnessed; the auto-vs-manual policy trade-off is now opinion-with-evidence.

Lab 3 — CI Hands Off the Cluster (90 min) — the pipeline inversion

  1. Modify your Module 6 CD workflow: after build+push, instead of helm/kubectl, it clones myapp-config, edits the staging overlay's image tag (your k8s_bump.py from Module 11 — everything converges!), commits, pushes.
  2. Remove the kubeconfig/cluster credentials from CI entirely. Watch a full flow: code merge → image → config commit → ArgoCD auto-sync → staging rollout — with CI never touching the cluster.
  3. Promote to prod: PR the same tag change into overlays/prod, merge, press Sync in ArgoCD (read the diff first — that's the reviewed-plan moment).
  4. Rollback drill: git revert the prod tag commit, sync — old version back. Compare this against every rollback method you've learned (rollout undo, helm rollback, redeploy tag) and write which you'd reach for when. ✓ Deploy = merge. Rollback = revert. Credentials = gone from CI. The GitOps promises, checked off one by one.

Lab 4 — App-of-Apps Bootstrap (60 min)

  1. Root Application pointing at myapp-config/bootstrap/ which contains Application manifests for: api-staging, api-prod, and monitoring (kube-prometheus-stack via Helm-type Application).
  2. kind delete cluster → recreate → install ArgoCD → apply ONLY the root app → watch your entire platform reassemble itself. ✓ Time the from-nothing rebuild. That number is your disaster-recovery story.

Part E — Challenges

C1. Sync waves: annotate so the namespace/CRDs sync before workloads; prove ordering in the sync details. C2. ApplicationSet: generate staging+prod apps from one template with a list generator; add a fake third env by adding one list entry. C3. Argo notifications (or a webhook hack): Slack message on sync succeeded/failed for prod. C4. Secret strategy: pick sealed-secrets OR SOPS+age; encrypt your DB password INTO the config repo safely; document why plain Secret YAML in Git was never acceptable. C5. Postgres exporter + Grafana panel for replication lag and connections (Modules 10+12 combined), deployed via the App-of-Apps like everything else.


Part F — Break & Fix Scenarios

D1 — The broken manifest merge. Commit invalid YAML/schema to the config repo (bad indentation in the Deployment). What does ArgoCD show? Where's the error surfaced? Fix via revert vs fix-forward — do one of each.

D2 — Sync loop fight. Add an HPA AND a hardcoded replicas: in Git for the same Deployment with selfHeal on — watch ArgoCD and HPA fight (OutOfSync flapping). Fix properly (remove replicas from Git / ignoreDifferences). This exact conflict is a famous real-world gotcha.

D3 — Deleted namespace. kubectl delete ns staging (everything gone!). Recover using only ArgoCD. How long? What would this have been without GitOps?

D4 — The migration/deploy race. Ship a config change where the new image needs a migration that hasn't run (skip your pipeline's migrate step once, in staging). Reproduce the Module 10 boss-fight incident end-to-end — alert → logs → revert → fix pipeline. Write the postmortem; compare with your Module 10 one and note how much faster you were.

D5 — Backup restore under GitOps. Postgres data "corrupted" (drop a table). App is GitOps-managed but DATA isn't in Git — restore from Lab 1's backups while ArgoCD keeps the workloads steady. Articulate clearly: GitOps governs desired state of infrastructure/config, not data — backups still rule the data plane.


Part G — Interview Rehearsal (out loud)

  1. Backups: walk your full policy — schedule, storage, retention, tested restore, RTO/RPO numbers you measured, and the alert on silent failure.
  2. Replication vs backup; Multi-AZ vs read replica — what each is for.
  3. The "too many connections" incident: symptom → diagnosis query → arithmetic → PgBouncer. Tell it as a story.
  4. Zero-downtime column rename — narrate expand/contract with your lab evidence.
  5. Push CD vs GitOps pull: three advantages, one honest drawback (extra repo/process, sync-loop gotchas — cite D2).
  6. What do selfHeal and prune do? Why might prod stay manual-sync?
  7. Disaster: cluster is gone. Walk your recovery (App-of-Apps timing from Lab 4 + data restore from D5).

Done when

restore drill under 2 minutes cold, Lab 2 arithmetic memorized, Lab 3's inverted pipeline runs end-to-end, the from-nothing rebuild is timed, and G1/G7 flow as first-person stories — because now they are.


Final Integration Milestone (the last exercise of the whole program)

Run your complete platform for one week as if employed: GitOps-managed app + monitoring, nightly tested backups, one self-inflicted incident every other day (pick randomly from every module's Part D), postmortem each. At week's end, record a 10-minute screen walkthrough of the whole system for your portfolio. If you can narrate that video confidently — you're not preparing for the job anymore; you're doing it.