Sub topic 1
What PostgreSQL is and how clients talk to it
PostgreSQL is an open-source relational database server. You store data in tables and read or change it with SQL (Structured Query Language). This chapter covers the architecture you will use for the rest of the tutorial. It explains what runs when "PostgreSQL is running", what a client such as psql does, and how the two connect. With that model, the install and connection steps in later chapters make sense, and so do most of the errors you may see.
Prerequisites
This chapter assumes you have:
- Comfort using a terminal or command prompt, including running a command and reading its output.
- A basic idea of what a database and a table are: a table holds rows, and each row has the same named columns.
- Permission to install software on your computer. You do not need it yet, but the next chapter does.
You do not need PostgreSQL installed to read this chapter. The short examples are for later, when you have a server to try them on.
PostgreSQL is a server, not a file
Some databases, such as SQLite, are libraries that open a file inside your own program. PostgreSQL works differently. It is a long-running server program that owns your data files. Other programs never read those files directly. They send requests to the server over a connection, and the server reads and writes the files for them.
This design has several consequences:
- Many users and applications can use the same data at once. The server coordinates them and keeps their changes from corrupting each other.
- The server can run on a different machine from the client.
- Access control is enforced in one place, the server, because every request passes through it.
- The server must be running before anything works. A large share of beginner errors come from this, not from SQL.
The client/server model
Two roles take part in every session:
- The server is the PostgreSQL program that listens for connections, checks permissions, runs SQL, and stores data.
- A client is any program that connects to the server and sends SQL.
psqlis the command-line client that ships with PostgreSQL. Graphical tools, application code (Python, Java, Node.js), and migration tools are also clients. They all speak the same protocol.
The two sides communicate with PostgreSQL's wire protocol. This is a message format that runs over a network connection. Client libraries such as libpq (used by psql), JDBC, and psycopg implement it, so you rarely deal with it directly. Every client does the same four steps:
- Open a connection to a host and port, or to a local socket.
- Authenticate as a role (a database user).
- Send SQL statements.
- Receive results or an error, then close the connection.
What runs on the server
When people say "the PostgreSQL server", they mean a group of operating system processes:
- The postmaster is the main process (its executable is named
postgres). It listens for new connections, and it starts and watches the other processes. - A backend process is started for each client connection. It handles that client's SQL for as long as the connection lasts. PostgreSQL uses a process-per-connection model, not one thread per connection.
- Background processes do housekeeping. They include the checkpointer and background writer (which flush changed data to disk), the WAL writer (which writes the write-ahead log used for crash recovery), and the autovacuum launcher (which cleans up dead row versions).
You can see this on Linux or macOS with ps. Many postgres entries appear, one of them the postmaster, plus one for each open connection.
Because each connection costs a process and memory, connections are not free. The max_connections setting caps them, and its default is 100. Busy applications usually share a small pool of connections instead of opening a new one per request.
The cluster, databases, and roles
Three terms often confuse newcomers because they overlap with words from other systems:
- A cluster is one running PostgreSQL server instance and the data directory it manages. It has nothing to do with multiple machines. One cluster listens on one port.
- A database is a named container for tables and other objects inside a cluster. One cluster can hold many databases. A fresh install already includes
postgres,template0, andtemplate1. - A role is an identity that can own objects and hold privileges. A role that is allowed to log in is what other systems call a user. Roles belong to the whole cluster, not to a single database.
Each connection is tied to exactly one database, chosen at connect time. A normal query cannot reach tables in another database. To work in another database, you open a new connection to it, which is what the \c command in psql does. Roles work differently. The same role can connect to any database where it has permission.
| Concept | Scope | Example |
|---|---|---|
| Cluster | One server instance, one port | The server on port 5432 |
| Database | Inside a cluster | `postgres`, `firstdb` |
| Role | Whole cluster | `postgres`, `alice` |
| Table | Inside a database | `books` |
Later chapters cover roles and databases in more depth. For now, remember that a connection has a role and a database.
How a connection is found
A client needs to know where to connect. It has four main parameters:
- Host: the machine running the server, such as
localhost. - Port: the TCP port the server listens on. The default is
5432. - User: the role to log in as.
- Database: the database to connect to.
If you leave a parameter out, psql falls back to defaults. These include environment variables such as PGHOST, PGPORT, PGUSER, and PGDATABASE, and the name of your operating system user. This is why the same command can behave differently on two machines.
On Unix-like systems the host can also be a directory path, which makes the client use a Unix domain socket instead of TCP. A Unix domain socket is a local-only channel that appears as a file. On a local machine, connecting without -h often uses this socket. Connecting with -h localhost uses TCP. The two paths can have different authentication rules, so one may work while the other fails.
Who is allowed in
A reachable server does not mean you can log in. The server decides in two steps:
- Network access. By default, a new installation listens only on the local machine (
listen_addresses = 'localhost'). Remote clients cannot connect until an administrator changes this setting. - Authentication rules. A configuration file named
pg_hba.conflists which roles may connect to which databases from which addresses, and by what method (for example password,scram-sha-256, orpeer). The server checks the first matching rule. If none matches, the connection is rejected.
A third check applies after login. Even an authenticated role can only touch objects it has privileges for.
A first look from the command line
You will install PostgreSQL in the next chapter. Once you have, these commands show the client/server split. psql --version talks to nothing. It only asks the client program for its version. pg_isready contacts the server and reports whether it accepts connections.
psql --version
pg_isready
pg_isready -h localhost -p 5432
echo "exit code: $?"pg_isready returns exit code 0 when the server accepts connections. It returns 1 if the server is running but rejecting connections (for example during startup), 2 if there was no response, and 3 if no attempt was made, such as when the parameters were invalid. Scripts can use these codes to wait for a server.
Once connected with psql, you can ask the server about your own session:
SELECT current_user, current_database(), pg_backend_pid();
SHOW port;pg_backend_pid() returns the operating system process ID of the backend serving your connection. Open a second psql window and run it again. You will get a different number, which confirms that each connection has its own backend process.
Common misunderstandings
- "psql is PostgreSQL." It is only one client. The server can be running with no client installed, and a client can be installed with no server on the machine.
- "Installing the client installs the server." On some Linux distributions these are separate packages, so you may have
psqlbut nothing to connect to. - "The server is installed, so it is running." Installation and running are separate. A server that is not running produces connection errors that look like SQL problems.
- "A database is the same as a cluster." One cluster holds many databases, and a connection reaches only one of them at a time.
- "localhost and the default socket are equivalent." They use different transports and may match different
pg_hba.confrules.
Exercise
A teammate runs psql -h localhost -U alice -d sales and gets "connection refused". Based on this chapter, name two different things to check first, and say which part of the client/server model each one belongs to.
Show answer
First, check whether the server is running and accepting connections on that host and port (for example with pg_isready -h localhost -p 5432). This is the server side. A server that is stopped, or listening on a different port, refuses TCP connections. Second, check that the client is using the right host and port, and that the server's listen_addresses includes the address being used. This is the connection and network side. Authentication problems in pg_hba.conf or a wrong role or database produce different messages, such as "password authentication failed" or "database does not exist", not "connection refused".
Exercise
You are connected to a database named firstdb and want to query a table that lives in a database named salesdb in the same cluster. Why can't you query it directly, and what do you do instead?
Show answer
Each connection is tied to exactly one database, and a normal query cannot read tables in another database. Open a new connection to salesdb, for example by running \c salesdb in psql. Roles are cluster-wide, so your role can usually connect there if it has permission.