Why apps need databases

Reading · 5 min · Module 9, lesson 1 of 420 min left in this module

Module 9 · DatabasesLesson 1 of 4

Goal: Explain why an app's lasting data belongs in a database rather than in a server's memory or files.

Databases at a glance

Database
Keeps data safely outside your servers.
Data model
Tables, key-value pairs or documents.
Connection string
Where the database is, and the password.
Connection pool
Reused connections, within the database's limit.
Where an app's lasting data lives, and how the app reaches it.

Key idea

Servers are meant to be replaceable, and there are often several of them. So anything that must last, such as accounts, orders or messages, goes in a database: one shared place that every server reads and writes, and that outlives any server.

This is the last hop. The request has found an address, crossed TLS, passed the load balancer and reached a server. To answer "show me my orders", that server needs data it doesn't keep itself.

Why not keep it on the server?

Your app on localhost probably kept data in a variable, a JSON file or SQLite next to the code. Online, each of those breaks in its own way:

  • Memory is wiped when the process restarts, and every deploy restarts it.
  • The server's disk may not survive a replacement (lesson 1.3.1), and the other servers behind the load balancer can't see it.
  • Several servers writing one file overwrite each other's changes.

A database is a separate server whose whole job is data. Every app server connects to it over the network, so they all see the same orders.

What a database adds

Beyond storing data, a database does work you'd otherwise write yourself, badly:

  • Safe concurrent writes. Two customers buying the last ticket can't both succeed. A transaction makes a group of changes happen completely or not at all.
  • Queries. "Orders over $50 from last week" is one question, answered quickly with the help of indexes, not by reading every record.
  • Durability. Once a write is confirmed, it survives a crash. Backups and copies on other machines guard against losing the machine itself.

Who runs it

Running a database well means backups you've tested restoring, upgrades, monitoring and failover. Many teams use a hosted database from a provider that does this for them, and connect to it like any other database.

Check yourself

Your app keeps a list of signups in a variable. It works on localhost, but online the list keeps emptying. Why?