Skip to content
devops.academy

Module 12 (Supplement): Databases in Operations & GitOps Essentials

Goal

Two gaps between "knows the toolchain" and "job-ready." Part A: databases — you've run Postgres in containers; now learn to operate one (backups, restores, replication, migrations, connection limits — the stateful stuff that actually pages people). Part B: GitOps with ArgoCD — the modern standard for deploying to Kubernetes, and an increasingly expected line on DevOps CVs.


PART A — Databases for DevOps Engineers

You don't need to be a DBA. You need to be the person who can answer: is the database healthy, is it backed up, can we restore it, and why is the app saying "too many connections"?


A1. The Landscape (Know What You're Operating)

TypeExamplesOps personality
Relational (SQL)PostgreSQL, MySQLACID transactions, schemas, migrations — the default choice
Key-value / cacheRedisin-memory, blazing fast, often allowed to lose data
DocumentMongoDBJSON-shaped, flexible schema
Managed versionsAWS RDS/Aurora, ElastiCacheAWS runs patching/backups/failover — you configure and monitor

DevOps reality: use managed (RDS) in production whenever possible. Self-hosting a production database means you own backups, failover, patching, and 3 AM disk pages. The self-hosting skills below still matter — for dev environments, cost-constrained setups, interviews, and understanding what RDS does for you.

Postgres survival SQL (enough to be dangerous):

sql
\l                      -- list databases        (psql meta-commands)
\c appdb                -- connect
\dt                     -- list tables
SELECT count(*) FROM orders;
SELECT * FROM pg_stat_activity;          -- WHO is connected, running WHAT (your #1 ops view)
SELECT pg_size_pretty(pg_database_size('appdb'));

A2. Backups — The Skill That Saves Careers

Iron law: an untested backup is a hope, not a backup. Companies die from this (GitLab's famous 2017 incident: five backup mechanisms, none working).

Analogy

A database is the town's ledger office and backups are the notarized copies stored in a vault in another town. Everyone assumes the copies are fine — until the office burns down and someone opens the vault to find the pages blank. That's why a restore drill matters more than the backup job: you don't own a spare key until you've actually turned it in the lock.

Logical backups — pg_dump (portable SQL/archive)

bash
# Dump one database (custom format: compressed, selective restore)
pg_dump -h db.internal -U app -Fc appdb > appdb_$(date +%F).dump

# Restore (to a NEW db — verify before touching anything real)
createdb appdb_restore
pg_restore -d appdb_restore appdb_2026-07-07.dump

# The production nightly, composed from Modules 2+3+8:
pg_dump -Fc appdb | aws s3 cp - s3://myco-backups/db/appdb_$(date +%F).dump

Good for: daily backups, migrations between versions/hosts, single-table recovery. Limits: a point-in-time snapshot at dump start; restoring a big DB can take hours.

Physical backups & PITR (concept level)

Point-in-Time Recovery = base backup + continuous WAL (write-ahead log) archiving → restore to any second, e.g. "the moment before the bad DELETE at 14:32:07." Tools: pg_basebackup, pgBackRest/WAL-G. On RDS this is a checkbox — automated backups + retention give you PITR for free. Know the concept and the term; interviews ask.

Backup policy checklist (say this in interviews)

  1. Automated schedule (nightly dump + WAL/PITR, or RDS automated backups).
  2. Off-box, off-account storage (S3, versioned, encrypted, cross-region for DR).
  3. Retention: e.g. 7 daily / 4 weekly / 12 monthly (lifecycle rules).
  4. Restore drills — actually restore to a scratch instance monthly; measure how long it takes. That duration is your RTO (recovery time objective); the data you can afford to lose since the last backup point is your RPO. Business decides the targets; you engineer to them.
  5. Monitor the backup job itself (Module 10: alert on "backup did NOT run/succeed" — absence of success, not just presence of failure).

A3. Replication & High Availability

Streaming replication: a primary ships WAL to one or more replicas (standbys) that apply it continuously.

Analogy

Replication is a junior clerk copying every ledger entry into a second book in real time, so if the head clerk collapses, someone can step straight in mid-sentence. But note the crucial catch: if the head clerk writes "burn page 40", the copy clerk faithfully burns page 40 too. A live copy protects you from the clerk dying, never from the clerk making a terrible entry — that's still the vault's job (backups).

App

all writes go to the primary; reads can optionally be split to replicas

PRIMARY
streams the WAL to every replica
REPLICA-1
can serve reads
REPLICA-2
in a different AZ!

What it buys:

  • HA/failover: primary dies → promote a replica → app reconnects. RDS Multi-AZ automates exactly this (~1–2 min failover, DNS flips automatically) — this is why Module 8's reference architecture said Multi-AZ.
  • Read scaling: dashboards/reports hit read replicas, protecting the primary.

What you must know operationally:

  • Replication lag — replicas are slightly behind (usually ms, can grow under load). Consequence: user writes, next request reads a lagging replica, sees stale data. Monitor pg_stat_replication / RDS ReplicaLag; alert on growth.
  • Replication is not backup: DROP TABLE replicates instantly to every replica. You still need A2.
  • Failover ≠ magic: connections drop and must reconnect; in-flight transactions abort. Apps need retry logic (Module 11 patterns!).

A4. Connections & Pooling — The Classic Production Incident

Postgres spawns a process per connection; max_connections is typically 100–200. Now do the math from Module 7: 20 API pods × 10 connections each = 200 → "FATAL: too many connections" the moment HPA scales you up. This exact incident is a rite of passage.

Analogy

Database connections are the ledger office's service windows, and there are only so many. If every clerk in every branch insists on their own permanently-open window, the office runs out and slams the shutters — "too many connections". A connection pool like PgBouncer is the single receptionist who takes everyone's requests and shuttles them through a handful of windows, so a hundred clerks share ten windows instead of demanding a hundred.

Fixes, in order of correctness:

  1. App-side pool sizing — each pod's pool = small (5–10), and total pods × pool ≤ ~80% of max_connections. Do this arithmetic before setting HPA maxReplicas.
  2. PgBouncer — a lightweight proxy that multiplexes thousands of app connections onto tens of real ones. Standard component in front of busy Postgres (RDS Proxy is the managed equivalent — also smooths Lambda's connection storms).
  3. Raising max_connections is the last resort (each connection costs RAM).

Diagnose live: SELECT count(*), state FROM pg_stat_activity GROUP BY state; — a pile of idle connections = an app leaking them (not closing/pooling properly).

Related slow-DB triage (enough to be useful): pg_stat_activity for long-running queries; EXPLAIN ANALYZE <query> — a Seq Scan on a huge table usually means missing index; check cache hit ratio and disk I/O (Module 10 dashboards). You flag it with evidence; devs/DBAs fix the query.


A5. Schema Migrations — Where Databases Meet CI/CD

Code is stateless and rolls back in seconds (Module 6). The database remembers. Changing schema safely is a deploy-pipeline problem — your problem.

Analogy

Migrations are official amendments filed to the ledger's format, and they only work if applied in strict numbered order and never un-filed. You can't "roll back" an amendment that ripped out a column any more than you can un-shred a page — you file a new amendment that restores it. This is why the expand/contract dance exists: you add the new column before anyone stops using the old one, so both the outgoing and incoming clerks can keep working through the change.

Migration tools (Flyway, Liquibase, Alembic, framework-native like Django/Rails): versioned SQL files in Git, applied in order, tracked in a table so each runs exactly once:

migrations
V1__create_orders.sql
V2__add_index_orders_user_id.sql
V3__add_column_orders_flags.sql

Pipeline placement: run migrations as a step before the new app version receives traffic — a Job/init step in K8s, a pipeline stage in Module 6. (Remember the Module 10 incident where the missing migration caused the outage? This is the fix.)

The zero-downtime rule — expand/contract. During a rolling deploy, old and new code run simultaneously (Module 7). Therefore every migration must be compatible with both versions:

text
Renaming a column, the WRONG way:  ALTER TABLE ... RENAME email TO email_address;
→ old pods instantly crash: column "email" does not exist. Outage, mid-rollout.

The RIGHT way (expand → migrate → contract), over multiple deploys:
1. ADD new column; new code writes BOTH, reads old.        (deploy)
2. Backfill old → new in batches.                          (job)
3. New code reads new column.                              (deploy)
4. Much later: DROP old column.                            (deploy)

Additional safety: additive changes first; CREATE INDEX CONCURRENTLY (plain CREATE INDEX locks writes!); never a destructive migration in the same release that stops using the thing; and know that rollback of code ≠ rollback of schema — you roll schema forward with a fixing migration, which is exactly why backward-compatible steps matter.


A6. Redis in Operations (Quick but Necessary)

You've used Redis as a cache/session store since Module 5. Ops essentials:

  • Persistence modes: RDB (periodic snapshots — can lose last minutes) vs AOF (append-only log — safer, bigger). Pure cache? Persistence off is fine — losing it means a cold cache, not lost data. Session/queue store? You care.
  • Memory is the resource: maxmemory + an eviction policy (allkeys-lru for caches). No policy + full memory = writes start failing — a classic mystery outage.
  • KEYS * in production blocks the single-threaded server — the famous footgun; use SCAN.
  • Monitor: memory usage, evictions, hit ratio, connected clients (redis_exporter → your Module 10 stack).
  • HA exists (Sentinel/Cluster) — know the names; use managed ElastiCache in production.

PART B — GitOps with ArgoCD

B1. What GitOps Is (and Why It Won)

Module 6 deployed by push: the pipeline runs kubectl apply/helm upgrade at the cluster. It works, but: the pipeline needs powerful cluster credentials (attack surface), nothing prevents drift (someone kubectl edits prod and Git no longer matches reality), and "what's running where?" requires forensics.

GitOps inverts it — pull model:

A Git repo holds the desired state of the cluster (manifests/Helm values). An agent inside the cluster (ArgoCD) continuously compares desired vs live and converges them.

Analogy

Push deployment is a pilot reaching in from outside the plane to shove the controls; GitOps is autopilot flying from the filed flight plan. You never grab the stick — you amend the flight plan in Git, and the autopilot inside the cockpit continuously corrects the plane to match it. If a passenger nudges a control (a manual kubectl edit), autopilot quietly puts it back, because the plan, not the nudge, is the truth.

PUSH (classic CD)

CI → kubectl/helm → cluster
CI holds cluster credentials

PULL (GitOps)

CI → updates YAML → config repo
ArgoCD (in cluster) watches the repo → applies to cluster
credentials never leave the cluster

Consequences that made it the standard:

  • Git is the single source of truth — deploy = merge a PR; rollback = git revert; audit log = git log. (The GitOps promise from Module 1, fulfilled.)
  • Drift detection/correction: manual kubectl edit → ArgoCD marks the app OutOfSync and (if auto-sync) reverts it. Drift becomes impossible, not just discouraged.
  • Security: cluster credentials never leave the cluster; CI only needs Git push rights.
  • Disaster recovery: new cluster + point ArgoCD at the repo = entire platform rebuilds itself.

This should feel familiar: it's the Kubernetes reconciliation loop (Module 7) extended to Git, and the same philosophy as Terraform plan/apply (Module 9) and Ansible desired-state (Module 6). One idea, everywhere: declare state, let controllers converge.

B2. Repo Structure & the Image-Update Flow

Two-repo pattern (standard):

  • app repo — source code + Dockerfile + CI (developers live here)
  • config repo — k8s manifests / helm values per env (ArgoCD watches this):
config-repo
apps/api/baseKustomize base (or a Helm chart)
apps/api/overlays/stagingsmall per-env patches
apps/api/overlays/prod

The full modern pipeline, end to end:

text
1. Dev merges code PR  →  CI: test, build, push image myapp:v2.4.1 (Modules 5–6)
2. CI opens/commits a change to the CONFIG repo: image tag → v2.4.1
   (or Argo CD Image Updater automates this)
3. ArgoCD sees the config repo changed → shows OutOfSync → syncs (auto or on click)
4. Rolling update proceeds (Module 7), health assessed, UI shows green
Rollback = revert the config-repo commit. That's it.

Notice what CI stopped doing: touching the cluster. Its job now ends at "publish image, update desired state."

Analogy

The two-repo split is the difference between the flight-operations desk and the flight plan itself. Developers work at the ops desk (the app repo) building and testing the aircraft; the filed flight plan (the config repo) is a separate, tightly-controlled document that says exactly which aircraft flies which route today. The autopilot only ever reads the flight plan — so changing what flies means amending that one document, and the whole history of who changed the plan and when is right there in git log.

B3. ArgoCD Hands-On Core

bash
# Install (kind cluster from Module 7 is perfect)
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
kubectl port-forward svc/argocd-server -n argocd 8080:443
# UI at https://localhost:8080  (admin / initial secret from: 
#   kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d)

Analogy

Installing ArgoCD is fitting the autopilot unit into the cockpit and pointing it at where the flight plan is filed. From that moment nobody hand-flies: you show it the config repo, and it takes over the continuous job of comparing "planned route" against "where the plane actually is" and nudging the controls. The dashboard's green "Synced" light is simply the autopilot reporting that reality currently matches the plan.

An Application — ArgoCD's own CRD (Module 7's operator pattern — of course it is):

yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: api-prod
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/myorg/config-repo
    targetRevision: main
    path: apps/api/overlays/prod        # or a Helm chart: helm: { valueFiles: [values-prod.yaml] }
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  syncPolicy:
    automated:
      prune: true        # delete cluster resources removed from Git
      selfHeal: true     # revert manual drift automatically
    syncOptions: [CreateNamespace=true]

Concepts to be fluent in:

  • Sync status: Synced (live == Git) vs OutOfSync (diff — UI shows exactly which fields).
  • Health status: ArgoCD understands K8s kinds — Deployment progressing/degraded etc. Green ≠ just applied; green = actually healthy.
  • Automated vs manual sync: teams often auto-sync staging, manual-approve prod (a button in the UI, with the diff on screen — the "reviewed plan" idea from Module 9/Atlantis, for K8s).
  • selfHeal demo (do this — it's the "aha"): kubectl scale deploy api --replicas=10 by hand → watch ArgoCD snap it back to Git's 3 within seconds.
  • App-of-Apps / ApplicationSets: one Application that spawns many (whole-platform bootstrap; one template stamped across N clusters/envs).
  • Flux is the other major GitOps tool (more CLI/CRD-centric, no rich UI) — same model; know the name.

B4. Where Each Tool Now Sits (Your Final Mental Map)

LayerToolTrigger
Infrastructure (VPCs, clusters, RDS)Terraform (+ Atlantis)PR to infra repo
Cluster add-ons & apps (K8s objects)ArgoCD (+ Helm/Kustomize)PR to config repo
App build/test/publishGitHub Actions / JenkinsPR/merge to app repo
Inside legacy VMsAnsibleplaybook run (often from CI)
Observability of all of itPrometheus/Grafana/Lokialways-on

Every box: declarative state in Git, converged by machinery, watched by monitoring. That table is modern DevOps — and you now know every cell.


Hands-On Project (Do This)

Databases:

  1. Nightly pg_dump → S3 script (bash or Python — Module 11) with retention pruning; then restore it to a fresh container and verify row counts. Record your RTO.
  2. On RDS free tier: enable automated backups, create a read replica, watch ReplicaLag in CloudWatch; perform a Multi-AZ reboot-with-failover and time the app impact.
  3. Reproduce "too many connections" locally (set max_connections=20, run a connection-leaking loop); diagnose via pg_stat_activity; fix with PgBouncer in your Compose stack.
  4. Add Flyway (or Alembic) to your app repo; wire a migration step into the Module 6 pipeline; perform a column rename the expand/contract way across two deploys.
  5. Add postgres_exporter + redis_exporter to your Module 10 stack; alert on replication lag and "backup job didn't succeed in 26h."

GitOps: 6. Split your capstone into app repo + config repo (Kustomize base + staging/prod overlays). 7. Install ArgoCD on kind; create Applications for staging (auto-sync, selfHeal) and prod (manual sync). 8. Change CI's last step from helm upgrade to "commit new image tag to config repo"; watch the full flow: merge → image → config commit → ArgoCD sync → rollout. 9. Drift drill: kubectl edit something in staging, watch selfHeal revert it. Rollback drill: git revert the tag bump, watch prod return to the old version. 10. Bonus: App-of-Apps managing your whole stack (app + monitoring charts) from one root Application.

Self-Check Questions

  • Why is replication not backup? RPO vs RTO — who sets them, who engineers them?
  • What's PITR and what two ingredients enable it?
  • 20 pods × 10 connections vs max_connections 100 — what happens, and the three-tier fix?
  • Why does renaming a column break a rolling deploy, and what's expand/contract?
  • Why must CREATE INDEX in prod be CONCURRENTLY?
  • Push CD vs GitOps pull — three concrete advantages of pull.
  • What do prune and selfHeal each do? Why might prod stay manual-sync?
  • In the two-repo model, what exactly does CI commit, and what does it no longer need credentials for?


You've Completed the Curriculum — Now What?

With Modules 1–12 complete, your knowledge coverage is genuinely job-ready. The rest is keyboard hours. Turn it into something you can show:

  1. Build the capstone: one repo/org containing the full chain — app → Dockerfile → CI (tests + scans) → ECR → Terraform-provisioned EKS/ECS → Helm/ArgoCD deploy → Prometheus/Grafana/Loki → documented SLOs, backups, and a runbook. This single project answers 80% of interview questions with "let me show you."
  2. Write it up: README architecture diagram + a short postmortem of a failure you induced and fixed. Communication is half the job.
  3. Practice the stories: every module's "real scenario" (disk-full, CrashLoopBackOff, drift, rollback, alert fatigue, too-many-connections) is a stock interview question — rehearse them aloud.
  4. Keep going: DevSecOps, K8s certs (CKA), cost optimization (FinOps), and one cloud deeply before a second broadly.

Good luck — go build, break, and observe things.