📘 Visual Posts About Contact
Explore 📋 Cheat Sheets ✏️ Practice 🎮 Games 🎬 Simulations 🃏 Flashcards 🎯 Interactive Layers 📖 Storytelling
💜 Support my site

Databases & Data Servers

Module 13 of A-to-Z Server Admin SQL • Redis • Backups 2026 Updated

Every login, bank transfer, shopping cart, and server log lives inside a database. Learn why plain files fail under pressure, how SQL, NoSQL, and Redis work together, how to lock down database ports, and how to recover data to the exact second before a disaster.

Start Module 13 ↓
Web / App Server Private Subnet: 10.0.1.10 <1ms RAM SQL Write Redis Cache In-Memory Key-Value Port 6379 • Sessions Primary SQL DB PostgreSQL / MySQL Port 5432 / 3306 • ACID WAL Stream Read Replica (Sous-Chef) Handles Heavy SELECT Analytics Backup + PITR pg_dump / mysqldump

01 Why Files Aren't Enough (ACID Vaults)

A Database Server is specialized software that stores, indexes, and protects structured data so thousands of users can read and write at the exact same time without corrupting anything.

Beginners often ask: "Why can't my web app just save user data into a users.csv or orders.json file on the hard drive?" Saving to a plain file works for 1 person on a laptop—but the moment 500 customers click "Buy Now" at the same second on a server, plain files fall apart.

🏦 Real-World Analogy: Shared Excel Spreadsheet vs. Bank Vault

Imagine 100 cashiers trying to edit the same Excel file on a shared folder at the same time. Cashier A opens it, Cashier B overwrites A's changes, and if the power flickers mid-save, the whole file turns into unreadable garbage. A Database is a Bank Vault with Armored Tellers: every deposit and withdrawal is written to a tamper-proof ledger first, locked per-row so tellers never collide, and guaranteed to survive a sudden power outage.

PLAIN FILE (CSV / JSON) User A Writes User B Writes COLLISION & CORRUPTION Last writer wins; half-written bytes ✗ Slow: Must scan entire file to search ✗ No Locks: Concurrent edits destroy data ✗ Crash Risk: Power loss = broken file ACID DATABASE ENGINE Tx 1 (Row Lock) Tx 2 (Queued) WRITE-AHEAD LOG (WAL) All-or-nothing commits; B-Tree index ✓ Millisecond Lookups via B-Tree Indexes ✓ Safe Concurrency with Row-Level Locks ✓ Crash-Proof: WAL replays after reboot

The 4 ACID Guarantees

Whenever a relational database processes a transaction (like transferring $100 from Alice to Bob), it guarantees four strict rules known as ACID:

A

Atomicity

All or Nothing. If $100 leaves Alice's account, it must arrive in Bob's. If the server crashes halfway, the entire transfer rolls back so money never vanishes.

C

Consistency

Rules Always Hold. Database constraints (like balance >= 0 or unique emails) can never be broken, even by a buggy application.

I

Isolation

No Stepping on Toes. Two simultaneous transactions do not see each other's half-finished work until they officially commit.

D

Durability

Written in Stone. Once the database says "Committed", that data is flushed to disk (via the Write-Ahead Log) and survives power loss.

🧠 Memory Trick: "A Clean Icebox" (ACID)

Atomicity (All-or-nothing), Consistency (Check rules), Isolation (Independent lanes), Durability (Disk-saved forever). Just like a clean icebox keeps food fresh even if the kitchen gets busy, ACID keeps data uncorrupted.

02 Relational SQL vs. NoSQL & Redis Cache

Not all server data has the same shape or speed requirements. As a server administrator, you will routinely manage three distinct families of data servers: Relational (SQL), Document (NoSQL), and In-Memory Cache (Redis).

RELATIONAL (SQL) PostgreSQL • MySQL • SQL Server id email 101 [email protected] 102 [email protected] Strict Tables & JOINs • Rigid schema (columns fixed) • Strong ACID transactions • Best for: Banking, ERP, Users, Orders, Inventory DOCUMENT (NoSQL) MongoDB • DynamoDB { "id": 101, "tags": ["vip"], "theme": "dark" } Flexible JSON Docs • Schema-less (fields vary) • Easy horizontal sharding • Best for: Product catalogs, IoT events, CMS profiles IN-MEMORY CACHE Redis • Valkey SET sess:99 "ali" EXPIRE sess:99 3600 → 0.2ms (RAM!) RAM Key-Value Speed • Lives in RAM (not SSD) • Auto-expiring TTL keys • Best for: Login sessions, rate limits, leaderboards

Meet the Big Four Data Engines

Engine Category Where You See It Key Strength
PostgreSQL Relational (SQL) Linux cloud apps, SaaS, fintech Rock-solid ACID, rich indexing, JSONB support
MySQL / MariaDB Relational (SQL) WordPress, LAMP stacks, web apps Fast reads, ubiquitous hosting, simple replication
Microsoft SQL Server Relational (SQL) Windows Server, Active Directory apps, ERP Deep Windows/AD integration, enterprise BI
Redis / Valkey In-Memory Key-Value Front of SQL DBs as a speed layer Sub-millisecond RAM reads, TTL expiry, queues

⚠️ Redis is a Cache, Not Your Primary Vault!

Because Redis keeps data in RAM for extreme speed, a sudden server crash without persistence enabled wipes everything in memory. Use Redis to cache hot data (like user sessions or homepage products) so your PostgreSQL or MySQL database isn't hammered 10,000 times a second—never store your only copy of financial records in Redis.

03 Database Ports & Locking Down Access

Just like SSH listens on Port 22 and HTTPS listens on Port 443, every database server opens a specific TCP Port to accept queries. Leaving that port exposed to the public internet is one of the fastest ways to get breached by automated ransomware bots.

Database Server Default TCP Port Config Binding Risk If Exposed to 0.0.0.0
MySQL / MariaDB 3306 bind-address = 127.0.0.1 Brute-force & full table dump
PostgreSQL 5432 listen_addresses = 'localhost' Unauthorized SQL & RCE via extensions
MS SQL Server 1433 SQL Server Configuration Manager sa password spray & xp_cmdshell
Redis / Valkey 6379 bind 127.0.0.1 -::1 Often no password by default → instant takeover

🧠 Memory Trick: The 4 Golden Database Ports

MySQL = 3306 (Think "3-3-0-6, MySQL ticks") • PostgreSQL = 5432 (Countdown: 5-4-3-2, Postgres!) • SQL Server = 1433 (Windows Server enterprise) • Redis = 6379 (Spell MERZ on a phone keypad—named after an Italian singer!).

127.0.0.1 (Localhost) vs. Private Subnet

There are only two safe ways to expose a database port in production:

  • Single-Server Setup (127.0.0.1): If your web app and database live on the exact same server, bind the database to 127.0.0.1 (loopback). No outside computer on the internet or LAN can even see the port.
  • Multi-Server Setup (Private Subnet): When your app server and database server are separate machines, bind the database to its private IP (e.g., 10.0.2.20) and use a firewall (ufw, iptables, or Cloud Security Groups) so only the App Server's IP (10.0.1.10) can reach port 5432/3306.
PUBLIC INTERNET Scanner Bots 0.0.0.0/0 → :5432 Real Users HTTPS :443 ONLY UFW BLOCK APP SERVER Private IP: 10.0.1.10 Nginx + App Code Accepts :443 Connects to DB ALLOW ISOLATED DB TIER 10.0.2.20 (No Public IP) PostgreSQL :5432 Only 10.0.1.10 allowed Redis :6379 Auth + Private Subnet

✓ Checkpoint: Can you...

  • State why a plain CSV file fails when 100 users write at the same time?
  • Explain the difference between PostgreSQL (SQL) and Redis (In-Memory Cache)?
  • Match Ports 3306, 5432, 1433, and 6379 to their database engines?

04 Primary-Replica Replication & Read Scaling

What happens when your website grows from 100 visitors to 100,000 visitors—or when a single database server's hard drive fails? If you only have one database server, your entire business goes offline.

Primary-Replica Replication solves both performance and survival by keeping one authoritative Primary database and one or more live copies called Replicas.

👨‍🍳 Real-World Analogy: The Head Chef & Sous-Chefs

In a busy restaurant, only the Head Chef (Primary) is allowed to update the master recipe book (INSERT, UPDATE, DELETE). Every time the Head Chef writes a change, an assistant immediately photocopies that page to the Sous-Chefs (Read Replicas). Waiters asking "What's in this dish?" (SELECT reads) can ask any Sous-Chef, taking massive pressure off the Head Chef—and if the Head Chef gets sick, a Sous-Chef can be promoted to take over.

Application / Load Router Splits Writes vs. Reads WRITES (INSERT/UPDATE) READS (SELECT) PRIMARY (Head Chef) Read + Write Authority Writes WAL / Binlog Single source of truth Async Stream READ REPLICA 1 (Sous-Chef) Read-Only • Web Dashboards READ REPLICA 2 (Failover) Read-Only • Reporting / Standby

Two Things Every Admin Must Know About Replication

  • Replication Lag: Replicas are usually updated asynchronously (a few milliseconds behind the Primary). If a user updates their profile picture and immediately refreshes from a Replica, they might briefly see the old picture.
  • Replication is NOT a Backup: If an admin accidentally runs DROP TABLE users; on the Primary, that destructive command replicates to every Replica in milliseconds—wiping them all! That's why you still need real backups.

05 Practical Lab: Logical Backups & Point-in-Time Recovery

A database without tested backups is a ticking time bomb. In server administration, you combine two layers of protection: Logical Backups (portable SQL snapshots) and Point-in-Time Recovery (PITR) (continuous transaction logs).

POINT-IN-TIME RECOVERY (PITR) TIMELINE 00:00 AM Full Snapshot pg_basebackup 06:00 – 11:41 Continuous WAL Logs Every INSERT/UPDATE saved 11:41:59 ✓ STOP REPLAY HERE Zero data loss! 11:42:00 💥 DROP TABLE! Skipped on restore Formula: PITR = Midnight Base Backup + Replay WAL Logs up to 1 second before the mistake

Essential Backup & Restore Commands

Below are the real-world commands every Linux server admin uses to create compressed logical backups and restore them cleanly:

# 1. PostgreSQL: Logical compressed backup (custom format)
pg_dump -U postgres -Fc -f /backups/appdb_$(date +%F).dump appdb

# PostgreSQL: Restore into a fresh database
createdb -U postgres appdb_restored
pg_restore -U postgres -d appdb_restored /backups/appdb_2026-11-29.dump

# 2. MySQL / MariaDB: Consistent online backup (no table locks!)
mysqldump -u root -p --single-transaction --routines --triggers appdb | gzip > /backups/appdb_$(date +%F).sql.gz

# MySQL / MariaDB: Restore from compressed backup
gunzip < /backups/appdb_2026-11-29.sql.gz | mysql -u root -p appdb

🚨 Never Forget --single-transaction in MySQL!

Running plain mysqldump without --single-transaction can lock your InnoDB tables while copying, freezing your live website for every customer until the backup finishes.

📝 Practice Problem: Stopping a Data Breach & Restoring Safely

Scenario: You inherit a production Ubuntu server running PostgreSQL and Redis alongside a web app on the same machine. Running ss -tulnp shows PostgreSQL (5432) and Redis (6379) listening on 0.0.0.0, and there are zero automated backups.

Task: What two immediate network/config changes lock down both databases, and what command creates a compressed PostgreSQL backup of shopdb?

Show Solution

1. Bind to Localhost (127.0.0.1): Since the web app is on the same server, set listen_addresses = 'localhost' in postgresql.conf and bind 127.0.0.1 -::1 (plus requirepass) in redis.conf, then restart both services.

2. Verify Firewall: Ensure ufw denies incoming 5432/tcp and 6379/tcp from the internet.

3. Compressed Backup: Run pg_dump -U postgres -Fc -f /backups/shopdb.dump shopdb and copy it offsite (e.g., S3 or another server).

06 Knowledge Check

Test your Module 13 Database knowledge — click an option for instant feedback. Score: 0 / 4

1. In the ACID model, which property guarantees that a bank transfer either completes 100% or rolls back completely if the server crashes midway?

Atomicity✅
Isolation❌
Durability❌

2. Which database engine stores data primarily in RAM for sub-millisecond caching and runs on default port 6379?

PostgreSQL❌
Redis✅
Microsoft SQL Server❌

3. Why is Primary-Replica replication NOT a substitute for backups?

Because Replicas cannot answer SELECT queries❌
Because an accidental DROP TABLE on the Primary is immediately copied to all Replicas✅
Because replication only works for 24 hours❌

4. An admin accidentally deleted a critical table at 11:42:00. Which recovery strategy lets you restore the database to 11:41:59 with zero data loss?

Point-in-Time Recovery (Base Backup + WAL/Binlog replay)✅
Changing bind-address to 127.0.0.1❌
Restarting the Redis cache service❌