Database Hosting

Updated · 15 min read
mediumPostgreSQL 18sqlhostingcloudmanaged-databaseserverlessdevopsinterview

Database hosting means deciding where the database server runs and who looks after it. Up to now, every example ran on a copy of the Fee Tracker inside your browser. A real app needs a database that is always on, reachable by the app, backed up and kept up to date. There are three common ways to get one. You can run PostgreSQL yourself on a server you control, rent a managed database from a cloud provider who runs it for you, or use a serverless database that grows and shrinks with the work and can sleep when nobody uses it. In this lesson, we will compare the three, ask a database about itself with SQL, measure how much space the Fee Tracker really needs, list what a cloud bill is made of, and pick a sensible setup for a small project.

In One Minute

  • Self-managed: you install, patch, back up and repair PostgreSQL yourself. Most control, most work.
  • Managed: the provider runs the server, backups, patches and failover; you still own the schema, queries, users and data.
  • Serverless: a managed database that scales its computing power with demand and, on many services, pauses when idle.
  • The bill is mostly compute (the size of the server, by the hour), storage (by the gigabyte per month), plus backups, I/O, replicas and data sent out.
  • For a small project, a small managed database is usually the right start.

Three Ways to Host a Database

The three options differ mainly in who does the routine work: installing, patching, backing up and recovering.

OptionWhat it isExamples
Self-managedYou install the database on a machine you run: a server in an office, a rented virtual machine, or a containerPostgreSQL on a Linux VM, MySQL in Docker
ManagedThe provider runs the database server for you; you connect to it like any otherAmazon RDS, Amazon Aurora, Google Cloud SQL, Azure Database for PostgreSQL and MySQL, Azure SQL Database
ServerlessA managed database whose computing power is added and removed automaticallyAurora Serverless v2, Azure SQL Database serverless, Neon

Amazon RDS runs PostgreSQL, MySQL, MariaDB, SQL Server, Oracle and Db2 for you. Aurora is Amazon's own engine that speaks the PostgreSQL or MySQL protocol, with storage that is copied across several data centers. Google Cloud SQL runs PostgreSQL, MySQL and SQL Server. On Azure, Azure SQL Database is a managed SQL Server engine, and Azure Database for PostgreSQL and for MySQL run those engines. Smaller companies such as Neon and Supabase offer hosted PostgreSQL aimed at developers.

Who does what: the provider takes over the machine, but the schema, queries and data access are always yours

Ask the Database About Itself

Whatever the hosting, the first thing to check after connecting is which version you are on and which database and user you are using. These queries work on any PostgreSQL server, including the one in Try it:

SQL▶ Try it
SHOW server_version;
 
SELECT current_database() AS database_name,
       current_user       AS connected_as;
Output
 server_version
----------------
 18.7
(1 row)
 
 database_name | connected_as
---------------+--------------
 postgres      | postgres
(1 row)

Explanation: SHOW server_version returns the PostgreSQL version. The Try it database is PostgreSQL 18; a managed service shows whatever version you chose when you created it, and it keeps the minor version (the number after the dot) up to date if you allow it. current_user here is postgres, the superuser.

On a managed service, you don't get a true superuser. The provider keeps that for itself, so it can run the server safely. Instead, the first user you create gets a strong but limited admin role: rds_superuser on Amazon RDS, cloudsqlsuperuser on Cloud SQL, and azure_pg_admin on Azure. It can create databases, roles and approved extensions, but it can't read server files or change the operating system.

Settings the Host Controls

The size of the server decides several important settings: how many connections it accepts and how much memory it uses. You can read them with SQL on any host:

SQL▶ Try it
SELECT name, setting, unit
FROM pg_settings
WHERE name IN ('max_connections', 'shared_buffers', 'work_mem', 'TimeZone')
ORDER BY name;
Output
      name       | setting | unit
-----------------+---------+------
 TimeZone        | UTC     | NULL
 max_connections | 100     | NULL
 shared_buffers  | 16384   | 8kB
 work_mem        | 4096    | kB
(4 rows)

Explanation: max_connections is how many sessions may be open at once (100 is PostgreSQL's default). shared_buffers is the memory PostgreSQL keeps for table pages, counted in 8 kB blocks: 16,384 blocks is 128 MB. work_mem is the memory one sort or hash may use before spilling to disk, here 4,096 kB, or 4 MB. On your own server you change these in the postgresql.conf file. Managed services don't let you edit that file; you change settings through parameter groups on RDS and Aurora, database flags on Cloud SQL, and server parameters on Azure. Many services set max_connections and shared_buffers from the server's memory, so a bigger server gets bigger values.

Most managed servers run in UTC. That is a good default, because TIMESTAMPTZ values are stored as a moment in time whatever the setting. A session can still show times in a local zone. Navika lives in Dallas:

SQL▶ Try it
SHOW TimeZone;
 
SET TimeZone = 'America/Chicago';
 
SELECT TIMESTAMPTZ '2025-12-03 18:00:00+00' AS paid_at_in_dallas;
Output
 TimeZone
----------
 UTC
(1 row)
 
SET
 
   paid_at_in_dallas
------------------------
 2025-12-03 12:00:00-06
(1 row)

Explanation: The same moment, 18:00 UTC, prints as 12:00 noon in Dallas, six hours behind UTC in December. SET changes only this session, which is how an app shows local times without changing the server.

How Much Space Does the Data Need?

Storage is billed by the gigabyte each month, so it helps to measure your data instead of guessing. PostgreSQL can report the size of a database and of each table:

SQL▶ Try it
SELECT pg_size_pretty(pg_database_size(current_database())) AS whole_database;
 
SELECT relname AS table_name,
       pg_size_pretty(pg_total_relation_size(oid)) AS size_with_indexes
FROM pg_class
WHERE relname IN ('students', 'courses', 'enrollments', 'payments', 'cities')
ORDER BY relname;
Output
 whole_database
----------------
 7720 kB
(1 row)
 
 table_name  | size_with_indexes
-------------+-------------------
 cities      | 24 kB
 courses     | 40 kB
 enrollments | 24 kB
 payments    | 24 kB
 students    | 40 kB
(5 rows)

Explanation: The whole database is under 8 MB, and most of that is PostgreSQL's own system catalog, which every database has. Each Fee Tracker table takes a few small 8 kB pages for its rows and indexes, so a handful of rows still costs a minimum of 24 to 40 kB. Small tables tell you little about growth. To plan, fill a copy of a table with many rows and measure it:

SQL▶ Try it
CREATE TABLE payments_test (LIKE payments INCLUDING ALL);
 
INSERT INTO payments_test (payment_id, student_id, course_id, amount_usd, due_on, paid_on, method)
SELECT g, 101 + g % 3, 1 + g % 6, 100 + g % 400,
       DATE '2025-01-01' + g % 365, DATE '2025-01-01' + g % 365,
       (ARRAY['card', 'check', 'cash'])[1 + g % 3]
FROM generate_series(1, 100000) AS g;
 
SELECT pg_size_pretty(pg_relation_size('payments_test'))       AS rows_only,
       pg_size_pretty(pg_indexes_size('payments_test'))        AS indexes,
       pg_size_pretty(pg_total_relation_size('payments_test')) AS total,
       pg_total_relation_size('payments_test') / 100000        AS bytes_per_payment;
Output
CREATE TABLE
 
INSERT 0 100000
 
 rows_only | indexes |  total  | bytes_per_payment
-----------+---------+---------+-------------------
 6672 kB   | 2208 kB | 8904 kB |                91
(1 row)

Explanation: LIKE payments INCLUDING ALL copies the columns, defaults, checks and the primary key, but not the foreign keys, which is why random student and course pairs are allowed here. 100,000 payments take about 8.7 MB with the primary key index, roughly 91 bytes per payment. So a million payments need around 90 MB, and ten million around 900 MB. Add room for more indexes, the transaction log, dead rows waiting for VACUUM (MVCC), and growth, and a small project fits easily in the smallest storage size most providers sell.

Real sizes: 100,000 payments take 8,904 kB, about 91 bytes each

What Costs Money

A cloud database bill has a few parts. Prices change often and differ by region, so check the provider's price calculator rather than remembering numbers.

Part of the billWhat you pay forHow to keep it small
ComputeThe server size (CPU and memory), charged by the hour or second while it runsStart small; resize later. Serverless can pause when idle
StorageGigabytes allocated (or used, on some services), per monthMeasure your data; delete what you don't need
I/OReads and writes to disk, on some services and plansIndexes and better queries read less (Writing Fast Queries)
BackupsBackup storage beyond what is included, and long retentionKeep only the retention you need
High availabilityA standby copy in a second data center, which you also pay forUse it for production, not for test databases
ReplicasEach read replica is another server (Replication and Scaling)Add one only when reads really need it
Data transferData sent out of the provider's network, often free coming inKeep the app and the database in the same region

The biggest surprises are usually things left running. A test database nobody uses still bills by the hour, and a high-availability standby roughly doubles the compute part. Many providers offer a free tier or starting credits for small databases, with limits that change from time to time; read the current terms before relying on them.

The parts of a database bill and the usual surprises

Connecting Safely

An app connects to a hosted database with a host name, a port, a database name, a user and a password, often written as one connection string:

text
postgresql://fee_app:<password>@db.example.com:5432/feetracker?sslmode=verify-full
PieceMeaning
fee_appThe database user the app logs in as
<password>Kept in a secret store or an environment variable, never in the code
db.example.com:5432The server's host name and port; 5432 is PostgreSQL's default
feetrackerThe database on that server
sslmode=verify-fullEncrypt the connection and check the server's certificate

Three rules cover most of database hosting security:

  1. Keep the database off the public internet when you can. Put it on a private network that only the app's servers can reach. If it must be public, allow only known addresses.
  2. Encrypt the connection. sslmode=require encrypts it; verify-full also checks that you reached the real server.
  3. Give the app its own limited user, not the admin user (Users, Roles and Privileges).
SQL▶ Try it
CREATE ROLE fee_app LOGIN PASSWORD 'change-me';
GRANT SELECT, INSERT, UPDATE ON students, courses, enrollments, payments, cities TO fee_app;
 
SET ROLE fee_app;
 
SELECT count(*) AS payments_visible FROM payments;
 
DROP TABLE payments;
Output
CREATE ROLE
 
GRANT
 
SET
 
 payments_visible
------------------
                7
(1 row)
 
ERROR:  must be owner of table payments

Explanation: The app's user can read and change rows, but DROP TABLE fails because only the table's owner (or a superuser) may drop it. If the app is ever tricked into running the wrong SQL (SQL Injection), the damage stays limited. On a real server, the password goes into the secret store, not a script like this one.

Choosing for a Small Project

For most small projects, start with the smallest managed database from the cloud you already use, in the same region as the app. It gives you automatic backups, patches and a way to restore, without running a server. Then adjust:

SituationA good fit
Learning, or a project on your own laptopPostgreSQL installed locally, or in a container
A small app with steady trafficThe smallest managed instance; turn on automated backups
Traffic that is spiky, or idle most of the dayA serverless database that pauses when idle (expect a short delay on the first query after a pause)
A production app that must stay upA managed database with a high-availability standby
Strict rules about where data lives, or special extensionsSelf-managed, or a managed service that supports them, in the right region
A simple path to a first choice

Before you choose, check four things: the PostgreSQL versions the service offers, the extensions it allows (such as pg_stat_statements or PostGIS), how backups and point-in-time restore work (Backup and Restore), and how easy it is to move away. A plain pg_dump works on every PostgreSQL host, so your data is never locked in.

Common Mistakes

Using the admin user in the app. One bug or injected query can then drop tables. Give the app its own limited user.

Leaving the database open to the whole internet. Use a private network, or at least allow only known addresses, and always encrypt connections.

Forgetting test databases. They bill by the hour whether anyone uses them or not. Stop, pause or delete them.

Putting the app and database in different regions. Every query travels farther, and data sent between regions can cost money.

Assuming managed means backed up forever. Automated backups are kept for a limited number of days, and deleting the database may delete them too. Test a restore before you need it.

Guessing the size. Measure bytes per row with realistic data, then choose storage and plan growth.

Interview Corner

What is the difference between self-managed and managed database hosting?

With self-managed hosting you install, patch, back up and repair the database server yourself. With a managed service the provider does that work, including backups and failover, while you still own the schema, queries, users and data.

What does serverless mean for a database?

The provider adds and removes computing power automatically as load changes, and you pay for what is used. Many serverless databases can pause when idle, which saves money but makes the first query after a pause slower.

Can you change postgresql.conf on Amazon RDS or Cloud SQL?

Not directly. You change settings through the service's own tools: parameter groups on RDS, database flags on Cloud SQL, server parameters on Azure. You also don't get a true superuser; the admin role is limited.

How would you estimate storage for a table that will have ten million rows?

Load a realistic sample, such as 100,000 rows, measure pg_total_relation_size, divide by the row count, and multiply up. Then add room for more indexes, the log, dead rows and growth.

Practice

Challenge: Before choosing a storage size for the Fee Tracker, Srihitha wants to know how much space 50,000 enrollments need. Create a test copy of enrollments, fill it with 50,000 rows, and report the total size and bytes per enrollment.

Show solution
SQL▶ Try it
CREATE TABLE enrollments_test (LIKE enrollments INCLUDING ALL);
 
INSERT INTO enrollments_test (student_id, course_id, enrolled_on, status)
SELECT g, 1 + g % 6, DATE '2025-01-01' + g % 365,
       (ARRAY['active', 'completed', 'dropped'])[1 + g % 3]
FROM generate_series(1, 50000) AS g;
 
SELECT pg_size_pretty(pg_total_relation_size('enrollments_test')) AS total,
       pg_total_relation_size('enrollments_test') / 50000          AS bytes_per_enrollment;
Output
CREATE TABLE
 
INSERT 0 50000
 
  total  | bytes_per_enrollment
---------+----------------------
 3688 kB |                   75
(1 row)

The primary key of enrollments is the pair (student_id, course_id), so each test row uses a different student_id to keep the pairs unique. An enrollment row is smaller than a payment (75 bytes against 91), but its two-column primary key index takes a bigger share of the total: about 30 percent, against 25 percent for payments.

Quick check: Database hosting

4 questions
1With a managed database, which job is still yours?
2How do you change a setting such as work_mem on Amazon RDS?
3A test copy of a table holds 100,000 rows in 8,904 kB. About how much will 1 million rows need?
4Which is a common surprise on a database bill?

Key Takeaways

You want toUse
See the server versionSHOW server_version;
Read a settingSHOW work_mem; or pg_settings
Measure a databasepg_size_pretty(pg_database_size(current_database()))
Measure a table with its indexespg_total_relation_size('payments')
Show times in a local zone for one sessionSET TimeZone = 'America/Chicago';
Connect securelyA connection string with sslmode=verify-full and a secret-stored password

Was this tutorial helpful?

Lesson 98 of 115