PostgreSQL roles and least privilege

PostgreSQL roles and least privilege explains how to separate owner, application and人 access so each account gets only what it needs. It covers the design, the build sequence and the checks a self-hosted team should run.

On this page

Why PostgreSQL roles and least privilege matter for your self-hosted database

Least privilege in PostgreSQL means every login role holds only the grants its work requires: table and schema privileges, membership in predefined roles, and default privileges for objects created later, with superuser reserved for a few administrators. A redesign is worth planning when one shared login serves an application, a migration job, analysts and administrators, or when application code connects as a superuser. If you cannot list which role owns each schema and which roles can write to it, you already have the problem.

Roles are defined once for the whole cluster, so a role created in one database exists in every database on that server. Privileges are different: they are granted per database, per schema and per object, such as a table, sequence or function. That split is the source of most surprises. A role that can connect to a database and has been granted nothing else may still reach objects through the public pseudo-role or through default privileges that a previous administrator set. Before changing anything, export the current grants for each database and confirm which roles own objects, which roles are members of other roles, and which accounts carry the superuser attribute.

The redesign question is who should own the schema objects and who should only use them. Owner roles usually hold no login at all, while application and reporting roles receive narrow grants on the objects they touch. Confirm the exact behavior of predefined roles such as pg_read_all_data and pg_maintain against the version you run, since they grant broad access and belong only in roles that truly need it. Also confirm how your team's migration tool connects, because it often needs owner-level rights during deployments and should not keep them in steady state.

Which role pattern fits which access need

This table compares the common PostgreSQL role patterns by purpose, the privileges each should hold and when it fits. Read each row as a boundary: the further a role reaches beyond its job, the larger the blast radius if its credentials leak. The main takeaway is that superuser and broad predefined roles should be rare, named and reviewed, while owner, migration, application and reporting roles should each have a narrow, documented grant set.

Role patternWhat it is forPrivileges it should holdWhen it fits
Owner roleOwns databases, schemas and tables so DDL has one accountable identityOwnership of its objects and CREATE on its schema; no login used by applicationsSchema changes and object ownership; keep it non-login or used only by deployment tooling
Migration roleRuns schema migrations during deploymentsDDL rights on the objects it changes, granted for the migration window and revoked afterwardVersioned migrations run by CI/CD; avoid reusing the owner or application login
Application roleConnects the running service to its dataSELECT, INSERT, UPDATE, DELETE on specific tables and USAGE on needed sequences; no DDLEvery service account; one role per application or per trust boundary
Read-only reporting roleSupports dashboards, analysts and BI toolsSELECT on named schemas or tables; no write or DDL rightsAnalytics and reporting; consider a replica for heavy queries
Predefined role (pg_read_all_data)Grants read access to all tables, views and sequences across the clusterMembership only where a broad audit or support function truly needs cluster-wide readsScoped operational or audit roles; confirm the grant's reach against your data classification before use
Predefined role (pg_maintain)Permits maintenance commands such as VACUUM and ANALYZE without ownershipMembership for maintenance accounts or scheduled jobs, not for application loginsOperations teams running routine maintenance; confirm the command list for your PostgreSQL version
Superuser accountBypasses permission checks and can change server configurationReserved for break-glass administration, kept out of applications and daily toolingEmergency administration with audited, time-limited use; confirm what superuser can still reach in your setup

Predefined roles to use before granting broad rights

PostgreSQL ships predefined roles that grant broad access to all data or to maintenance functions. Each one is a shortcut that can replace a narrower grant, so the cards below cover the roles most often granted to applications and people, and the risk each one carries.

pg_read_all_data

Grants read access to all tables, views and sequences in the cluster, including schemas the role would not otherwise see. It suits a reporting or audit account that must read everything, but it is a poor fit for an application that only queries one schema. Before granting it, confirm the exact objects it covers for your PostgreSQL version in the role list and check whether a per-schema SELECT grant would do.

Predefined roles docs

pg_write_all_data

Grants insert, update and delete on all tables in the cluster, and it builds on the read rights of pg_read_all_data. An application that holds it can alter or erase data in every schema, including tables owned by other applications. Treat it as a privilege for a small number of trusted administrative accounts, and use table-level grants for application writes.

pg_maintain

Allows vacuum, analyze, cluster, refresh materialized views, reindex and lock tables without owning them. Operators running routine maintenance can use it instead of superuser or ownership. Confirm which commands your PostgreSQL version includes, because a role that can lock tables can still cause an outage if it runs during peak load.

pg_monitor and pg_read_all_stats

The monitoring roles expose statistics views and, in the case of pg_read_all_stats, the detailed statistics for sessions owned by other users, including the queries they run. Monitoring agents often need these roles, but the query text can contain sensitive values. Confirm which views each role unlocks, and give the exporter its own login rather than a shared administrator account.

pg_signal_backend and pg_execute_server_program

pg_signal_backend lets a role cancel or terminate sessions owned by other non-superuser roles, which is useful for operators clearing a stuck connection. pg_execute_server_program allows running programs on the database host through COPY and related commands, which is a path to the operating system. Grant the first only to operators, and avoid the second for any application role.

Confirm each role before granting

Predefined roles change between major versions, so the list that applies to a 14 cluster may differ from a 17 or 18 cluster. Query the catalog to see the roles on your server, read the documentation for that version, and test the grant in a non-production cluster. Record which application or person holds each role and review those grants on a schedule.

Public schema permissions and default privileges

PostgreSQL has a special pseudo-role named PUBLIC. Every role is a member of PUBLIC, so privileges granted to PUBLIC apply to every login role in the database cluster, including roles created later. The public schema is the default schema in new databases, and its access rules have historically been permissive, so a role that can connect to a database may be able to create objects there unless the grants are changed. Review these defaults in each database, not only in the template database, because objects and grants are per database. Confirm the exact default for the PostgreSQL version you run in the release notes and the documentation for your version before you change anything.

  • Check PUBLIC grants: Query the information_schema and pg_catalog views for privileges held by PUBLIC on databases, schemas, tables and functions.
  • Revoke CREATE on the public schema: Use REVOKE CREATE ON SCHEMA public FROM PUBLIC; in each database that does not need general object creation.
  • Restrict CONNECT on databases: Revoke the default connect privilege from PUBLIC where only named roles should reach a database.
  • Review function execute rights: Some functions grant EXECUTE to PUBLIC by default, so check functions added by extensions.
  • Test with a low-privilege role: Log in as an ordinary application role and attempt the operations you expect to be blocked.

After changing PUBLIC grants, confirm that each application can still perform its intended reads and writes, because some older applications depend on implicit access.

How to redesign roles without breaking applications

This sequence moves PostgreSQL from shared superuser and owner-based access to owner, group and application roles with explicit grants, and it proves each application still works before the old access is removed.

  1. Inventory existing roles, grants and superuser accounts

    Start by listing every login role, group role, and database object owner in each cluster. Query pg_roles for rolsuper, rolcreatedb, rolcreaterole and rolbypassrls, then query information_schema.table_privileges and the schema privileges for each database. Record which applications connect as which role, and which people hold superuser or shared login accounts. The output is a written inventory with one row per role and one row per application connection path. The step is done when someone outside the database team can read the inventory and identify every account that can bypass checks.

  2. Map each application and person to a required need

    For each row in the inventory, decide what the connection actually needs: read on specific schemas, write on specific tables, schema migrations, maintenance, or administration of the server. Compare this with the predefined roles PostgreSQL provides, such as pg_read_all_data, pg_write_all_data and pg_maintain, and note where a predefined role is broader than needed. Confirm the exact privileges of each predefined role against the current PostgreSQL documentation for your major version. The output is a mapping table that the application owners and the database team have both reviewed and signed off.

  3. Create owner and group roles without login

    Create a non-login owner role for each application database or schema, and group roles for read and write access, such as app_readonly and app_readwrite. Set NOLOGIN on these roles so they cannot be used directly, then grant the group roles to the login roles that applications and people use. Keep the owner role separate from any login role so that schema changes and data access can be granted and revoked independently. The check is a query against pg_roles showing each group role with rolcanlogin set to false, and a membership query showing which login roles belong to each group.

  4. Move object ownership to the owner role

    Transfer ownership of databases, schemas and tables from the current bootstrap or superuser account to the owner role, using ALTER DATABASE, ALTER SCHEMA and ALTER TABLE ... OWNER TO. Check sequences, views, functions and types too, because ownership determines who can change and replace them. Run the changes in a maintenance window where the application's migration tool can still run as the owner. The check is a query against pg_class, pg_namespace and pg_proc that returns no objects still owned by a superuser or by a login role that is not meant to own them.

  5. Apply grants and default privileges

    Grant the group roles only the privileges mapped in step two, using explicit GRANT statements on each schema, table, sequence and function. Set ALTER DEFAULT PRIVILEGES for the owner role so that tables created later by migrations receive the same grants automatically. Review the public schema: on recent PostgreSQL versions, CREATE on the public schema is restricted, but confirm the behavior in your version and revoke any broad grants that remain. The check is a query against information_schema.role_table_grants and pg_default_acl that matches the mapping table line for line.

  6. Revoke superuser and bypass attributes from applications

    Remove SUPERUSER, BYPASSRLS and CREATEROLE from every application login role with ALTER ROLE, and keep administrative access in a small set of named administrator accounts that are used for break-glass work. Confirm that the application does not depend on superuser behavior, such as creating extensions or changing server settings, and move any such tasks into a controlled migration role. The check is a query on pg_roles where rolsuper and rolbypassrls are false for all application logins, and a log review confirming no superuser sessions remain from application hosts.

  7. Test each service with its new role

    For each application and each person group, open a connection with the new login role and run the operations the service performs in normal use: reads, writes, background jobs, and the migration tool. Test denied paths as well, such as a read-only role attempting an insert, and confirm that the error is the expected permission denial. Repeat the test in a non-production environment that matches production grants. The output is a test record per service that lists the operations, the role used and the result, and it is complete when every service passes and every expected denial occurs.

  8. Review the catalog and schedule drift checks

    Once the services pass, review the final catalog against the approved mapping: role attributes, group memberships, object owners, default privilege entries and public schema grants. Save the queries as a script and store the output as a baseline. Schedule the same script to run regularly and alert when a new superuser, a new login role outside the inventory, or an object owned by an unexpected role appears. The step is complete when the baseline is stored, the owner of the check is named, and the first scheduled run matches the baseline.

How owner, group and login roles connect

The diagram starts with the owner role, which holds schemas and tables and is never used to log in. Group roles such as read and write hold privileges, a migration role runs schema changes, and individual login roles inherit group membership instead of receiving grants directly. Superuser sits outside this path and should be reserved for break-glass administration. Check that default privileges are set for each owner, so objects created later follow the same model.

Owner, group and login roles, with superuser kept outside the normal grant path.

Security risks to review in a least-privilege design

Most PostgreSQL privilege problems come from a few habits: running applications as superuser, sharing logins, and letting schema rights and default privileges spread further than intended. Each risk below names the control that prevents it and a check you can run against your own cluster to confirm the control holds.

Applications connecting as superuser

A superuser bypasses every privilege check in the database, so an application or injected query running under that role can read, change or drop any object. Give each application its own login role with only the grants its workload needs. To verify, query pg_roles for rolsuper on every application role and confirm that the only superuser accounts are named administrators used for maintenance.

Authentication methods docs

Shared login accounts

When several services or people use one database login, logs cannot show who ran a query, and revoking one credential breaks everything that uses it. Create one role per service and one role per person, and keep administrators on named accounts. To verify, list roles that can log in and match each one to an owner, a service or a documented exception.

DDL rights leaking into application roles

If an application role owns tables or holds CREATE on a schema, it can alter or drop objects, change their definitions, or create objects that other roles then trust. Keep schema ownership with a migration or owner role and grant the application only SELECT, INSERT, UPDATE or DELETE on the tables it uses. To verify, check table and schema owners in pg_tables and pg_namespace and review has_schema_privilege results for application roles.

Broad grants on PUBLIC

Privileges granted to the PUBLIC pseudo-role apply to every role in the database, including roles created later. Review default rights on the public schema and revoke CREATE from PUBLIC where applications do not need it, then grant access to named roles. To verify, inspect nspacl and the ACL columns on databases and functions for entries granted to PUBLIC.

Unreviewed default privileges

ALTER DEFAULT PRIVILEGES decides what rights new tables and functions receive, so a forgotten entry can expose every object created later by a given role. Record each default privilege rule with the role it applies to, and review them after each migration or new schema. To verify, query pg_default_acl and compare each entry against the intended design.

Predefined roles granted without review

Roles such as pg_read_all_data and pg_maintain give broad access across many objects, which is useful for monitoring or maintenance but excessive for applications. Grant them only to named operational accounts and record the reason. To verify, list memberships in pg_auth_members for each predefined role and confirm every member has a documented need.

High availability docs

What teams ask before hiring help with PostgreSQL role design

How much effort does a PostgreSQL role redesign take, and what drives it?

The effort depends mostly on how many applications connect to the database, how many schemas and objects each one touches, how many migrations or scripts assume current grants, and how strict your change control is. A cluster with a few applications and one schema is a short exercise. A cluster with dozens of services, shared schemas and ad hoc superuser logins takes longer because every grant has to be traced to a real need before it is removed. Ask any partner for a quote built from a written scope that lists applications, databases, schemas and the approval steps for each change. No effort figure is given here because it depends on your environment.

What does the client need to provide for a role design engagement?

Plan to provide read access to the system catalogs and current privilege state, a list of applications and the database accounts each one uses, and a named owner for every application who can confirm what it needs. You will also need change windows for revoking privileges, a test environment that mirrors production roles, and someone who can approve changes to shared schemas. Without application owners, the team has to guess which grants are needed, and removing a privilege that is still in use is the most common cause of rollback.

Can our internal team design PostgreSQL roles without outside help?

Yes, a capable internal database team can design roles, especially if it has time to test each change against every application. The work is mostly careful inventory and staged testing rather than exotic configuration. Outside help tends to pay off when the team lacks time to trace dependencies, when many applications share a database, or when auditors will expect a documented model with evidence. Whichever path you choose, the output should be a role hierarchy, a grant matrix and a tested change plan.

How should we handle applications that depend on owning database objects?

Start by finding out which accounts own tables, functions and schemas, and whether those accounts are also used to log in. Application runtime roles should usually be granted only the data privileges they need, while a separate owner role holds the objects and runs migrations. Where an application currently depends on ownership, plan a transition: create the owner role, move ownership through a scheduled change, then grant the runtime role only the privileges it uses. Test migrations and rollback steps before the change window, because ownership changes can break deployment pipelines.

What should we confirm about our PostgreSQL version before redesigning roles?

Confirm the exact major version and whether it is still supported, because the predefined roles and default privilege behavior you rely on depend on the version. PostgreSQL 14 is listed as supported until November 12, 2026, and older versions are unsupported, so an unsupported cluster may need an upgrade before or alongside the role work. Also check whether password authentication uses SCRAM, since PostgreSQL 18 deprecated MD5 password authentication. Confirm the version against the PostgreSQL versioning policy and your vendor packages.

Does removing superuser use from applications and admins break things?

It can, if scripts, extensions or backup jobs quietly depend on superuser rights. The safer path is to list every login that holds superuser or broad privileges, identify what each one does, and replace those rights with narrower roles such as predefined monitoring or maintenance roles where they fit. Test backups, replication setup and monitoring agents after each change. Keep a break-glass administrator account with a documented, audited procedure rather than leaving everyday logins with superuser rights.

Will a role design work also cover our audit and compliance evidence?

A role design can produce the records auditors usually ask for, including a role hierarchy, the grant matrix, approval records for changes and tested evidence that applications still work. DeployOpen prepares systems, controls and evidence for compliance assessments, but it does not issue audit reports or certifications. Independent auditors and certification bodies make those determinations. Ask the partner to confirm in writing which artifacts they will deliver and how they will be kept under version control.

Limits and what to confirm in your environment

The design in this topic depends on details that vary by PostgreSQL version, pooler configuration, and identity setup. The cards below list what to confirm before you finalize role grants, and who to check with for each item.

PostgreSQL version and predefined roles

Predefined roles such as pg_read_all_data and pg_maintain are added or changed between major versions, so the set you can grant depends on your server. Confirm the exact role names and what each one covers on your version. Your current major version also determines how long you receive security fixes, so check the support window before you design around it. Use the version-specific role list from the vendor documentation, not a memory of an older release.

Oldest supported major version
14
Versioning policy

Extension ownership rules

Who owns an extension, and whether it can be created by a non-superuser, varies by extension and by how the extension was packaged. Some extensions create objects in the public schema, and the owner of those objects can affect who can change them later. Test extension creation and drop under the roles you plan to use, and record which role owns each extension in your environment.

Pooler and proxy login behavior

Connection poolers such as PgBouncer authenticate clients and then open server connections under a different login, so the role seen by PostgreSQL may not match the role the application used. Confirm how your pooler maps client logins to server logins, whether it supports the authentication method you chose, and whether session settings such as SET ROLE survive pooling. Check this against the pooler's own configuration reference for your installed version.

PgBouncer documentation

Directory and SSO role mapping

When login comes from LDAP, Kerberos, certificates or OAuth, PostgreSQL still needs a database role for each identity, and the mapping from directory group to role is maintained outside the database. Confirm which system is the source of truth for who holds a role, how removals propagate, and what happens to sessions and pooled connections when an account is disabled. Verify each mapping with a test login from a user who should be denied.

Authentication methods

Runtime DDL in applications

An application that creates tables, indexes or functions while it runs needs privileges that a read-write application role should not hold. Find out whether any migration, reporting or background job issues DDL at runtime, because that usually forces a broader grant than the rest of the application needs. Ask the development team to list every statement type their code issues, and separate schema migration from ordinary data access before granting anything.

Owner and migration role separation

Schema owners, migration tooling and application logins often end up as the same account over time. Confirm which role owns each schema and object, which role runs migrations in each environment, and whether anyone can connect as the owner in production. Your deployment tooling and change process determine this, so check them directly rather than assuming the separation from the design holds.

How DeployOpen scopes and delivers PostgreSQL role work

DeployOpen plans PostgreSQL role work as part of an implementation in infrastructure you control, whether that is your cloud accounts, your data centers or an air-gapped network. Most engagements are fixed-scope, which means the databases in scope, the roles to be designed, the applications and people affected, the deliverables and the timeline are agreed in writing before work starts. Because role design touches every application that connects to a database, the scope should list each service account, each team and each database that will be changed, so the quote reflects the real amount of work rather than a general estimate.

In practice, role work usually includes separating owner roles from application login roles, reviewing GRANT statements and default privileges for objects created by migrations, tightening schema permissions, and checking where people or jobs still connect as superusers or hold predefined roles such as pg_read_all_data or pg_maintain that exceed their needs. It also includes migrating existing grants without breaking applications, testing that each application role can still do what it must, and documenting the final model so your team can review and maintain it. Ask for test evidence from a non-production environment and a rollback plan in the written scope.

A quote follows from the written scope, so the useful inputs are the number of databases and schemas, the number of application and human access paths, the state of your current grants and whether you need the work reviewed by an outside party. Ongoing support, upgrades and periodic access reviews are available as a retainer, which suits teams that add new applications or change PostgreSQL versions often. DeployOpen prepares systems, controls and evidence for compliance assessments, but independent auditors and certification bodies issue any audit report or certification. Confirm the deliverables and acceptance criteria with DeployOpen before signing, since they define what you receive.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.