Should an API Gateway Connect Directly to a Database? Patterns and Risks

API7.ai

September 15, 2026

API Gateway Guide

An API gateway should normally connect to an application service, function, or supported service API—not directly to a database. The service layer owns domain authorization, transactions, schema evolution, connection pools, and stable API semantics. Putting those responsibilities in the gateway couples public traffic handling to storage internals and expands the blast radius of gateway configuration.

A narrow exception can be reasonable for a controlled, read-only lookup or a managed service integration, but it still needs a bounded data contract, least-privilege identity, pooling, timeouts, overload protection, and an explicit migration path. “The plugin can open a database connection” is a technical possibility, not an architecture recommendation.

Key Takeaways

  • Keep transactional database access behind the service that owns the data and business rules.
  • Prefer HTTP, function, workflow, queue, or managed service integrations whose failure and authorization contracts are visible.
  • Never derive a table, query, tenant, or authorization decision from untrusted request fields.
  • A direct read path still needs connection limits, query limits, cache behavior, and schema-change ownership.
  • Test absent credentials, pool exhaustion, database failover, slow queries, duplicate requests, and rollback before production.

Separate Gateway and Data Responsibilities

An API gateway is optimized for request admission and traffic policy: TLS termination, authentication, coarse authorization, routing, quotas, transformations, and observability. A data-owning service is optimized for domain invariants: which rows a caller may read, which state transition is valid, and whether several writes commit together.

AWS documents API Gateway integrations with Lambda functions, HTTP endpoints, AWS service actions, and mock endpoints. Apigee describes a proxy as a facade that forwards to a TargetEndpoint or backend service. These models keep a clear protocol contract between the gateway and backend. They do not require the gateway to become the database client.

flowchart LR
    C[Client] --> G[API gateway\nidentity, admission, routing]
    G --> S[Domain service\nauthorization and transactions]
    S --> D[(Database)]
    S --> Q[Queue or workflow]
    G --> O[Gateway telemetry]
    S --> A[Domain audit]

Gateway telemetry records the request path. Domain audit records who changed which business object and why. Neither log replaces the other.

Why Direct Database Access Becomes Fragile

Domain Authorization Moves to the Wrong Layer

A validated token can establish a caller identity, but it rarely proves permission to update a particular invoice, workspace, or account. If gateway code turns a public X-Tenant-ID header into a database predicate, the caller may choose another tenant unless trusted authentication logic replaces and validates that value.

Pass a minimal, gateway-created identity context to the service. The service must still check tenant membership and object ownership against its authoritative data.

Connections Become Request-Path Capacity

Gateway workers handle many concurrent connections. Database connections are much scarcer. Opening or holding a database connection per request can exhaust the pool before CPU or network capacity is reached. A slow query then occupies gateway resources, increases latency, and can amplify retries.

Use a service-owned bounded pool, query deadlines, concurrency limits, and load shedding. A gateway timeout only stops waiting; it does not prove that a database operation was canceled or rolled back.

Transactions and Retries Lose Context

Gateways may retry selected upstream requests, while database drivers and applications have separate retry behavior. Retrying a write without an idempotency contract can duplicate an operation. Splitting a transaction across gateway scripts makes atomicity, compensation, and audit ownership harder to reason about.

Keep write retries and transactions in the domain service. The gateway should use bounded upstream retries only where the method and application contract make replay safe.

Schema Changes Leak Into the Public Edge

If routes contain SQL, column names, or database-specific error handling, a schema migration becomes a gateway deployment. That breaks the stable API boundary and gives the gateway credentials broader access than traffic routing requires.

Choose a Safer Pattern

RequirementPreferred pathWhy
Transactional read or writeGateway → domain service → databaseKeeps authorization, transactions, and schema ownership together
Short serverless operationGateway → function → databaseIsolates database client and IAM policy from gateway runtime
Long-running or bursty writeGateway → service → queue/workflow → workerDecouples request admission from processing capacity
Public, read-heavy reference dataGateway/CDN cache → read API or materialized viewReduces database load with an explicit staleness contract
Cloud service actionSupported gateway service integrationUses a documented service API and scoped cloud identity

The Amazon API Gateway HTTP API documentation describes Lambda and routable HTTP endpoints as backend paths. A function can own a short database interaction, but it still needs connection reuse, concurrency control, least-privilege credentials, and transaction semantics.

Apache APISIX supports custom and serverless functions inside request phases. That extensibility does not make a gateway worker a suitable home for arbitrary database clients. Blocking calls, secrets, driver lifecycle, and failure behavior remain the operator's responsibility.

Treat Exceptions as Products, Not Shortcuts

Consider a direct read only when all of these are true:

  • the dataset is read-only from this path;
  • the query set is fixed and parameterized;
  • the credential can access only the required view or procedure;
  • the result has a defined size, timeout, and cache policy;
  • connection and query concurrency are bounded below database capacity;
  • callers cannot select arbitrary tables, columns, tenants, or predicates;
  • schema ownership and rollback are assigned;
  • failure returns a controlled response without exposing driver or schema details.

Even then, a small read service is often easier to test, scale, secure, and replace.

The following is a configuration excerpt, not a complete deployment. It keeps APISIX 3.18.0 on an HTTP boundary and sends inventory requests to a service that owns database access:

routes: - id: inventory-api uri: /inventory/* methods: [GET] upstream: type: roundrobin nodes: "inventory-service.internal:8080": 1 #END

In file-driven standalone mode, APISIX requires the #END marker before loading a complete apisix.yaml, as documented in deployment modes. The excerpt intentionally contains no database address or credential. Authentication and rate-limit plugins would be added according to the deployment's identity contract.

Validate the behavior in a non-production environment:

  1. Send a valid request and confirm the service—not the gateway—records the database operation.
  2. Send an unauthenticated request and confirm it is rejected before the service.
  3. Try a caller-supplied tenant header and confirm it cannot override verified identity context.
  4. Exhaust a test database pool and verify bounded latency, no retry storm, and a controlled error.
  5. Fail over the database and confirm in-flight and retried writes preserve the application's idempotency contract.
  6. Deploy an incompatible schema change in test and verify the service protects the public contract.

Production Checklist

  • Is the database hidden behind the service that owns its schema and invariants?
  • Does the service recheck tenant and object authorization?
  • Are queries parameterized, bounded, and protected by deadlines?
  • Are connection pools and request concurrency sized together?
  • Are writes idempotent where clients or infrastructure may retry?
  • Are credentials short-lived or rotated, scoped, and absent from gateway files and logs?
  • Can a schema or route change be rolled back independently?
  • Do gateway telemetry and domain audit events correlate without treating a request ID as trusted identity?

FAQ

Can an API gateway technically connect to a database?

Some gateways can run custom code that opens a database connection. That capability does not provide domain authorization, safe pooling, transactions, or schema ownership automatically.

Is direct access acceptable for read-only data?

Sometimes, but only with a fixed query contract, least privilege, strict capacity bounds, and clear schema ownership. A read service or cache is usually the safer default.

Does a gateway timeout cancel the database query?

Not necessarily. It may only stop the gateway from waiting. Cancellation and transaction outcome depend on the service, driver, database, and connection state.

Next Steps

Design safe gateway timeouts and retries, apply concurrency budgets and backpressure, and define fine-grained authorization ownership before exposing a data-backed API.

Share article link