LiteLLM with a PostgreSQL read replica

How to point LiteLLM's read-only queries at a PostgreSQL reader endpoint while writes stay on the primary, what that changes for availability and auth, and what to confirm before you build it.

On this page

When a LiteLLM PostgreSQL read replica takes load off the writer

A platform team whose LiteLLM database is busy with key lookups and spend queries should consider a reader endpoint before anything else. Setting DATABASE_URL_READ_REPLICA alongside DATABASE_URL sends find, count, group_by and raw reads to the reader, while creates, updates, deletes and transactions stay on the writer. The split is worth testing when the primary's load is dominated by read traffic from authentication and budget checks on every request, or by dashboards and reports that scan spend tables, and the writes themselves are not the bottleneck. Confirm this first by looking at the database's own statistics on the primary during peak hours, not by assumption.

The split is premature when the limit is writes. Spend writes are often the constraint on a busy gateway, and a reader does nothing for them. The sizing guide covers how sustained requests per second, storage per logged request and connection pool math drive the writer's size, and whether a read replica is the right next step. If the writer is short on CPU or I/O because of inserts and spend updates, move to a larger writer or tune the spend update batching first, then revisit reads. Adding a replica also adds a second database endpoint to monitor, size and secure, so the operational cost should be justified by measured read load.

Plan for the reader to lag behind the writer. Reads that follow a write, such as a newly created key being used immediately, may not see the change yet, so confirm with the vendor and in a test environment how LiteLLM behaves for those paths before relying on the reader for them. The reader can be a managed read replica, such as an Aurora reader, or a PostgreSQL hot standby that you run. Each needs its own authentication, whether password, IAM or Entra ID token, and the reader's role must have the privileges LiteLLM needs for reads. Test the reader with the same identity model you use for the writer, and confirm the fallback behavior by stopping the reader in a staging environment.

Configuration options and when each fits

This table compares three ways to wire LiteLLM to PostgreSQL: a single writer, a writer plus a separate reader URL, and a reader endpoint behind a managed cluster endpoint. Read each row to see what the option gives up in simplicity, how it handles replication lag and which authentication method it supports. The main takeaway is that a reader only helps if you have confirmed how stale spend views can be for your teams.

OptionSimplicity and setupReplication lag and spend viewsAuthentication and when it fits
Single DATABASE_URLOne connection string, one pool to size and monitor. No extra routing to reason about.Every read and write hits the primary, so spend and key views are current. Read load grows on the writer.Use the auth method the writer already supports, including IAM or Entra ID tokens if configured. Fits lower traffic or when the writer has spare capacity.
DATABASE_URL plus DATABASE_URL_READ_REPLICATwo URLs and two pools. LiteLLM sends find, count, group_by and raw reads to the reader and writes to the writer.Reads can trail the writer, so recently spent budgets or new keys may appear late on the reader. Confirm how long a stale view is acceptable for budget checks.Each URL carries its own credentials, so IAM or Entra ID token auth must be set up for both endpoints. Fits when reads are the bulk of database load.
Reader endpoint behind a managed cluster endpoint (for example, an Aurora reader)Application config stays fixed while the platform adds or removes readers behind one reader address. Failover and scaling are handled by the database service.Lag depends on the replica type and the platform's replication design. Measure lag on your own cluster before relying on spend views for enforcement.Requires the reader address to allow the same token or certificate auth as the writer. Confirm how the platform's failover changes the reader endpoint and whether connections recycle cleanly.
Fallback to writer when the reader is unavailableNo extra code path for the operator, but warnings appear in logs when the reader is down.Reads move back to the writer, so lag is not the issue during fallback but load on the writer rises. Plan writer capacity for that case.Fallback does not change auth. Test that the writer credentials still work when the reader is unreachable.
Connection pool sizingEach proxy worker opens pools for both endpoints, so the count of connections multiplies with replicas.Pool limits affect both endpoints. Check the managed database's maximum connection count against workers and replicas before rollout.Token-based auth adds token refresh behavior to pool health checks. Confirm refresh works for both pools.
What to confirm before choosingAsk whether the team needs near-real-time spend and budget enforcement or only periodic reporting.Measure replication lag under peak write load on your database, and decide the maximum lag each view can tolerate.Confirm the IAM or Entra ID token flow for each endpoint in a staging environment with the same proxy version you will run in production.

Setting up the reader and verifying the split

This sequence produces a LiteLLM gateway whose key lookups and spend reads go to a verified PostgreSQL hot standby, while writes stay on the primary and a reader outage falls back to the writer without an outage for callers.

  1. Provision the reader endpoint

    The platform or database team adds a PostgreSQL standby to the existing primary, or creates a managed reader (for example, an Aurora reader or a read replica on another managed service), in the same network path the gateway pods can reach. Confirm the major version matches the writer and that the reader is on a version still in support under the PostgreSQL versioning policy. The step is done when you have a separate hostname or endpoint for the reader that is distinct from the writer endpoint.

  2. Confirm the standby serves read-only queries

    Connect to the reader with psql or your cloud console and run a query that returns whether the server is in recovery. A hot standby reports that it is in recovery and accepts SELECT statements, but rejects writes such as CREATE TABLE or INSERT. Check replication lag from the primary before you point the gateway at it, because reads from a lagging reader will return older key and spend rows. The step is done when the reader answers a read query and refuses a write.

  3. Store both connection strings as secrets

    Add DATABASE_URL for the writer and DATABASE_URL_READ_REPLICA for the reader to your secret manager, not to plain environment files or the image. For managed databases that use IAM or Entra ID tokens, the secret or the startup wrapper must supply a token that is refreshed before expiry, and the database role must be granted connect and read rights on the reader. Restrict who can read these secrets, since the writer string grants write access. The step is done when the gateway deployment references both secret keys and no value appears in the manifest or pod spec in clear text.

  4. Apply the schema through the writer

    Run LiteLLM's database migration job against DATABASE_URL only. Schema changes are writes, so they must reach the primary, and the reader then receives them through replication. Do not point migrations at the reader, because the reader cannot accept DDL. The step is done when the migration job completes successfully and the tables created by the migration are visible from a read session on the reader after replication catches up.

  5. Start the gateway and check the startup logs

    Start the gateway with both variables set and read the startup logs from the first pod. A healthy start shows no read-replica warning. Then send a test request with a virtual key and confirm it is accepted. The step is done when the logs show a clean start, the request succeeds, and no warning about the reader appears in the first minutes of operation.

  6. Verify that reads hit the reader

    Enable statement logging or query monitoring on the reader for a short window, then send a key lookup request and a spend-related request through the gateway. Find the SELECT statements for the verification key or spend tables on the reader's logs, and confirm that the INSERT, UPDATE or transaction statements for spend appear only on the writer. Record the reader's query counts before and after so you can compare them later. The step is done when you can show reads on the reader and writes only on the primary.

  7. Test the startup warning for an unreachable reader

    In a non-production environment, point DATABASE_URL_READ_REPLICA at an unreachable host, restart a pod, and read its startup logs. LiteLLM should log a warning and route reads to the writer. Confirm that requests still succeed and that the warning appears in the log stream your alerting watches. Restore the correct value and restart. The step is done when you have captured the warning text, a successful request during the outage, and a clean restart after the fix.

  8. Test writer fallback during a reader interruption

    While the gateway is serving test traffic, stop or block network access to the reader for a short controlled interval, then restore it. Watch for the warning on reconnect, confirm that key lookups continue to succeed through the writer, and confirm that reads return to the reader once it is reachable again by checking reader logs. Note any errors in the gateway logs and any increase in writer load. The step is done when reads fail over to the writer without failed requests for callers and return to the reader after recovery.

How LiteLLM requests split between writer and reader

The diagram starts at the LiteLLM proxy workers, which hold both DATABASE_URL and DATABASE_URL_READ_REPLICA. Find, count, group_by and raw reads go to the reader endpoint, which serves the standby. Creates, updates, deletes and transactions go to the writer endpoint on the primary. The labeled fallback path shows that if the reader is unreachable at startup or during reconnects, LiteLLM logs a warning and sends reads to the writer. The replication link carries changes from the primary to the standby. Check that both endpoints sit inside the database network boundary and that each token-based login path is allowed by its network rules.

Reads go to the reader, writes go to the primary, with fallback to the writer.

IAM and Entra ID token auth for the writer and the reader

On AWS, Aurora PostgreSQL can accept IAM database authentication, where the application requests a short-lived token from AWS instead of holding a stored database password. The writer endpoint and the reader endpoint both need this configuration, and each identity that connects needs permission to connect as its own database user. Plan the two paths together so the gateway does not depend on a long-lived password for either one.

  • Database roles: create one PostgreSQL role for the writer path and one for the reader path, and enable IAM authentication on each role as the Aurora documentation describes for your engine version.
  • Least privilege: give the reader role only the read grants that find, count and group queries need, so a misrouted write fails at the database instead of succeeding quietly.
  • Task or pod identity: the ECS task role or the Kubernetes service account identity needs an IAM policy that allows database connect for the specific cluster resource and database user.
  • Endpoints: confirm the writer endpoint and the cluster reader endpoint in your connection settings, and confirm that the token is generated against the host you connect to.
  • Network path: security groups and subnet routes must allow the gateway to reach both endpoints.

Confirm with the LiteLLM release you run whether the proxy generates IAM tokens itself or expects a token in the connection string, and test both paths before go-live.

Security and operational risks of splitting reads

Sending reads to a replica changes where LiteLLM gets key and spend data, and it can fail in ways that are easy to miss. The cards below cover staleness, silent fallback, authentication during reconnects, grants, pool capacity and audit visibility, each with a check to run before and after enabling DATABASE_URL_READ_REPLICA.

Stale key and spend views

Replica reads can trail the primary, so a key that was just disabled, a budget that was just raised or a spend total that was just updated may look different to the reader path. PostgreSQL supports both synchronous and asynchronous replication, and the mode you choose sets how far behind the reader can run. Confirm the lag your replica runs at under peak load, and decide whether budget enforcement or key revocation should depend on writer reads only.

PostgreSQL replication docs

Silent fallback to the writer

If the reader is unreachable at startup or during reconnects, LiteLLM logs a warning and sends reads to the writer. This protects availability, but it also means the reader can be down for hours while traffic and read load quietly return to the primary. Alert on the fallback warning, not only on gateway health, and check primary connection headroom so the fallback does not exhaust the writer's pool.

Token refresh during reconnects

With IAM or Entra ID token authentication, each connection to the reader and the writer presents a short-lived token. A reconnect that fails to obtain a fresh token leaves the reader path broken, and the fallback behavior then hides the failure. Test a forced reconnect on each endpoint, confirm the identity used by the gateway can mint tokens for both hosts, and watch for authentication errors in the logs during rotation.

PostgreSQL auth methods

Least-privilege reader grants

The reader role only needs select rights on the tables LiteLLM reads for keys, teams and spend. Writes, schema changes and migrations should stay on the writer role. Grant the reader role select only, verify that a write attempted through the reader endpoint fails, and review grants after each LiteLLM upgrade, since new tables or queries can require additional rights.

Connection pool sizing per replica

Each proxy worker opens its own connections to the reader and the writer, so pool settings multiply with pod count and worker count. A reader sized for read traffic can still be overwhelmed if many workers reconnect at once after a failover or restart. Calculate the total connections each endpoint must accept, compare that with the managed database limit, and set a PgBouncer or equivalent layer where the total approaches the limit.

PgBouncer project

Audit visibility of query endpoints

When a key lookup or spend query is served by the reader, an investigation needs to show that. Without it, a stale decision cannot be traced to the endpoint that produced it. Ask which log fields, database logs or connection labels identify the endpoint for each query, and confirm that logs record writer and reader access separately so reviewers can reconstruct what each path returned.

Questions buyers ask about a LiteLLM read replica

What drives the cost of adding a LiteLLM read replica?

The main drivers are the size of the writer and reader instances, how many standbys you run, and how much setup your token authentication needs. Instance size follows the write load from spend updates and the read load from key lookups, which depend on how many proxy workers and requests you serve. Each extra standby adds recurring infrastructure cost for as long as it runs, while the setup work is mostly one-time. Ask any quote to separate the one-time build (routing configuration, IAM or Entra ID token setup, testing) from the recurring database hosting, and to state which instance classes and standby count it assumes. Sizing guidance for the database itself is covered in a sibling topic on sizing PostgreSQL for LiteLLM.

How long does it take to set up a LiteLLM read replica?

The duration depends on how many environments you have, whether the reader already exists, and how much of the token authentication work is new to your team. If a reader endpoint is already provisioned, the LiteLLM side is mostly one setting, DATABASE_URL_READ_REPLICA, alongside DATABASE_URL, plus verification. If you are creating the replica, setting up IAM or Entra ID token authentication for both endpoints, and testing fallback behavior, the work takes longer. No standard duration applies, so ask a partner for a timeline tied to a written scope that lists each environment, the database platform and the tests included.

What does our team need to provide before the work starts?

Your team needs to provide access to the PostgreSQL writer and reader endpoints, a test or staging environment that mirrors production routing, and the cloud IAM rights or Entra ID permissions needed to create and assign database authentication roles. You also need the current LiteLLM deployment details, including image version, how DATABASE_URL is injected, and where secrets are stored. Expect to supply a named contact who can approve changes to the database security configuration and a window for maintenance on the primary. Confirm the exact permission list with your cloud or identity team, because it depends on your platform and on how strictly your organization scopes IAM roles.

Can our own platform team build a LiteLLM read replica internally?

Yes, a team that already runs PostgreSQL, LiteLLM and cloud IAM can build it in-house, because the application change is small. The harder parts are the database side: deciding replication mode, confirming that reader lag is acceptable for key lookups and spend queries, and handling failover, which PostgreSQL does not perform on its own and which needs external tooling. Token authentication for both endpoints also needs careful review. If your team lacks one of these skills, a partner can cover that gap under a fixed scope. Either way, check the design with your database owner before cutting over.

Does a read replica reduce availability if the reader goes down?

It does not reduce availability, because LiteLLM falls back to the writer for reads when the reader is unreachable at startup or during reconnects. It logs a warning when this happens. The practical risk is different: during a reader outage, all read traffic lands on the primary, so the primary must have enough capacity for that combined load. Plan connection limits and instance size for the fallback case, not only for normal operation, and alert on the warning so the team knows the reader is out.

Does a PostgreSQL standby count change how we should size the reader?

Standby count changes both cost and failure behavior. PostgreSQL hot standby servers serve read-only queries, and replication can be synchronous, where a commit waits for standbys, or asynchronous. Synchronous replication adds write latency that scales with standby placement, which matters because LiteLLM writes spend updates to the primary. Asynchronous replication keeps writes fast but means a reader can lag slightly behind, so recent spend may not appear in reads immediately. Choose the replication mode with your database owner, and size the reader for the read volume it will carry, not only for a single standby.

How does a LiteLLM read replica change after a PostgreSQL or LiteLLM upgrade?

Each upgrade adds work to the replica setup. A PostgreSQL minor update replaces executables and requires a restart, and it does not change the storage format, but the reader and writer should be updated in a planned order. A major upgrade can use pg_dumpall and restore, pg_upgrade, or logical replication, and logical replication works between major versions with only several seconds of downtime. Check which PostgreSQL major versions are still supported on the versioning policy page before choosing a target. On the LiteLLM side, confirm that the release you run still reads DATABASE_URL_READ_REPLICA as documented, and retest token authentication after each change. Ask any partner to include upgrade retesting in the retainer scope.

Is IAM or Entra ID token authentication required for the reader?

No, token authentication is a choice, not a requirement for the read replica pattern itself. It is worth choosing when your policy forbids long-lived database passwords or when your identity provider already issues the tokens. PostgreSQL supports several authentication methods, including password, certificate, LDAP, GSSAPI and OAuth, so the right choice depends on the managed service you use and your identity model. Setup covers creating database roles that map to IAM or Entra ID identities, granting only the privileges the gateway needs, and making sure both endpoints use the same approach. Confirm the method your database platform supports before design starts.

How DeployOpen scopes and delivers a LiteLLM read replica

DeployOpen plans and implements self-hosted LiteLLM gateways inside the client's own infrastructure, including the database routing that sends reads to a PostgreSQL reader while writes stay on the primary. The work is scoped in writing before it starts, built and tested against the client's environment, and handed over with documentation and a runbook the client's team can operate.

How we scope

  • Map which LiteLLM read paths will use the reader and which writes stay on the primary
  • Confirm the PostgreSQL engine, replica type and whether IAM or Entra ID token auth is required
  • Agree the fallback behavior, monitoring expectations and who owns the reader endpoint
  • Record scope, deliverables and timelines in writing, since most engagements are fixed-scope

How we build

  • Configure DATABASE_URL and DATABASE_URL_READ_REPLICA with secrets held in your secret manager
  • Set up token-based database authentication for both writer and reader connections
  • Test reader outages and reconnects to confirm the writer fallback behaves as documented
  • Run load and failover checks against your real replica lag and connection limits

How we hand over

  • Document which query types go to the reader and which go to the writer in your environment
  • Deliver configuration as code with the settings, secrets references and network rules used
  • Provide a runbook covering replica lag, fallback warnings and reader endpoint changes
  • Walk your platform, database and security teams through the build and the evidence collected

How we support

  • Offer ongoing support, upgrades and continuous testing as a retainer after handover
  • Review LiteLLM release notes and PostgreSQL minor updates against your replica setup
  • Retest routing and authentication after LiteLLM upgrades or database maintenance windows
  • Ask for a written quote based on your scope before any support commitment begins

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.