---
title: "Should an API Gateway Connect Directly to a Database? Patterns and Risks - API7.ai"
description: "Decide when to keep databases behind services, how to handle narrow exceptions, and how to test identity, pooling, transactions, and failure behavior."
url: "https://api7.ai/learning-center/api-gateway-guide/api-gateway-database-access-patterns"
---

[Skip to article](#column-content)

Column contentsAPI Gateway Guide

[API Gateway Guide](https://api7.ai/learning-center/api-gateway-guide)

Search this column

01 Gateway Fundamentals

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=fundamentals)[1. What Is an API Gateway? API Gateway Software and Use Cases](https://api7.ai/learning-center/api-gateway-guide/what-is-an-api-gateway)[2. Why Do Modern Architectures Need an API Gateway?](https://api7.ai/learning-center/api-gateway-guide/why-do-modern-architectures-need-api-gateway)[3. Reverse Proxy vs Load Balancer vs API Gateway](https://api7.ai/learning-center/api-gateway-guide/api-gateway-vs-reverse-proxy-vs-load-balancer)[4. API Gateway and Microservices: Decoupling and Traffic Management](https://api7.ai/learning-center/api-gateway-guide/api-gateway-and-microservices)[5. Understanding Core API Gateway Features](https://api7.ai/learning-center/api-gateway-guide/core-api-gateway-features)[6. Open Source vs. Commercial API Gateways: How to Choose the Right One?](https://api7.ai/learning-center/api-gateway-guide/open-source-vs-commercial-api-gateway)[7. API Gateway vs Service Mesh: How to Choose?](https://api7.ai/learning-center/api-gateway-guide/api-gateway-vs-service-mesh)[8. Envoy vs NGINX, Java, and Go for API Gateways](https://api7.ai/learning-center/api-gateway-guide/nginx-vs-envoy-vs-java-vs-go)[9. Core Concepts of API Gateway: Service, Route, Upstream, Plugin, and Consumer](https://api7.ai/learning-center/api-gateway-guide/core-concepts-of-api-gateway)[10. API Gateway Comparison: Apache APISIX vs. Kong vs. Traefik vs. KrakenD vs. Tyk](https://api7.ai/learning-center/api-gateway-guide/api-gateway-comparison-apisix-kong-traefik-krakend-tyk)

02 Gateway Architecture and Design

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=architecture)[11. Deep Dive into API Gateway Architecture: Core Components and Design Principles](https://api7.ai/learning-center/api-gateway-guide/api-gateway-architecture)[12. Choosing the Right API Gateway for Your Architecture](https://api7.ai/learning-center/api-gateway-guide/api-gateway-monolithic-vs-microservices)[13. How to Architect an API Gateway for High Availability (HA)?](https://api7.ai/learning-center/api-gateway-guide/api-gateway-high-availability)[14. API Gateway Plugin Architecture: How to Extend and Customize Your API Gateway](https://api7.ai/learning-center/api-gateway-guide/api-gateway-plugin-system)[15. How Event-Driven Architecture (EDA) Works with API Gateway?](https://api7.ai/learning-center/api-gateway-guide/api-gateway-event-driven-architecture)[16. API Gateway Request Lifecycle Explained](https://api7.ai/learning-center/api-gateway-guide/api-gateway-request-lifecycle-explained)[17. Cloud-Native API Gateway on Kubernetes](https://api7.ai/learning-center/api-gateway-guide/cloud-native-api-gateway-kubernetes)[18. API Gateway Control Plane vs. Data Plane](https://api7.ai/learning-center/api-gateway-guide/api-gateway-control-plane-vs-data-plane)[19. How API Gateways Work with GitOps: Automating API Management](https://api7.ai/learning-center/api-gateway-guide/api-gateway-gitops-integration)[20. How to Perform A/B Testing and Canary Releases with an API Gateway](https://api7.ai/learning-center/api-gateway-guide/ab-testing-canary-release-api-gateway)

03 Gateway Setup and Traffic Handling

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=traffic-protocols)[21. How to Deploy an API Gateway on Kubernetes: Step-by-Step Guide for Engineers](https://api7.ai/learning-center/api-gateway-guide/deploy-api-gateway-on-kubernetes)[22. Hands-on Setup with Apache APISIX API Gateway](https://api7.ai/learning-center/api-gateway-guide/api-gateway-getting-started-guide)[23. API Gateway Auth: OAuth 2.0, JWT & OIDC with APISIX](https://api7.ai/learning-center/api-gateway-guide/api-gateway-authentication-apache-apisix-oauth-jwt-oidc)[24. Mastering Traffic Control: Efficiently Managing API Requests with Gateways](https://api7.ai/learning-center/api-gateway-guide/api-gateway-traffic-control-strategies)[25. Building Reliable API Gateways with Logging and Monitoring](https://api7.ai/learning-center/api-gateway-guide/api-gateway-logging-monitoring-best-practices)[26. Dynamic Routing in API Gateways: Best Practices for Flexible Traffic Management](https://api7.ai/learning-center/api-gateway-guide/api-gateway-dynamic-routing-management)[27. How API Gateways Support WebSocket](https://api7.ai/learning-center/api-gateway-guide/how-api-gateways-support-websocket)[28. API Gateway for GraphQL: Security, Cost, and Caching](https://api7.ai/learning-center/api-gateway-guide/api-gateway-handle-graphql)[29. How API Gateways Handle HTTP/3 QUIC Requests](https://api7.ai/learning-center/api-gateway-guide/api-gateway-http3-quic)[30. How API Gateways Handle MQTT Requests](https://api7.ai/learning-center/api-gateway-guide/api-gateway-mqtt)

04 Gateway Integrations, AI, and MCP

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=ai-mcp)[31. How API Gateways Handle gRPC Requests](https://api7.ai/learning-center/api-gateway-guide/api-gateway-grpc-support)[32. How API Gateways Implement Custom Plugins](https://api7.ai/learning-center/api-gateway-guide/api-gateway-custom-plugins)[33. How API Gateways Integrate with Kafka](https://api7.ai/learning-center/api-gateway-guide/api-gateway-kafka-integration)[34. How to Implement API Aggregation in API Gateways](https://api7.ai/learning-center/api-gateway-guide/api-gateway-api-aggregation)[35. How API Gateways Enable Serverless Architecture](https://api7.ai/learning-center/api-gateway-guide/api-gateway-serverless-architecture)[36. How API Gateways Proxy LLM Requests](https://api7.ai/learning-center/api-gateway-guide/api-gateway-proxy-llm-requests)[37. How API Gateways Enhance MCP Servers](https://api7.ai/learning-center/api-gateway-guide/api-gateway-enhance-mcp-server)[38. MCP Gateway vs MCP Proxy vs AI Gateway vs API Gateway](https://api7.ai/learning-center/api-gateway-guide/ai-gateway-vs-mcp-gateway-vs-api-gateway)[39. What Is an AI Gateway? Architecture and Benefits](https://api7.ai/learning-center/api-gateway-guide/what-is-an-ai-gateway)[40. What Is an MCP Gateway? Architecture, Use Cases & How It Works (2026 Guide)](https://api7.ai/learning-center/api-gateway-guide/what-is-mcp-gateway)

05 Gateway Performance

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=performance)[41. How API Gateway Reduces Latency: Performance Optimization Strategies](https://api7.ai/learning-center/api-gateway-guide/how-api-gateway-reduces-latency)[42. API Gateway Caching Strategy: Comprehensive Analysis and Implementation Guide](https://api7.ai/learning-center/api-gateway-guide/api-gateway-caching-strategy-analysis)[43. How to Optimize API Gateway Load Balancing: Advanced Strategies and Best Practices](https://api7.ai/learning-center/api-gateway-guide/how-to-optimize-api-gateway-load-balancing)[44. How API Gateway Efficiently Handles Large-Scale Traffic: Architecture and Strategies](https://api7.ai/learning-center/api-gateway-guide/how-api-gateway-handles-large-scale-traffic)[45. How to Improve API Gateway QoS: Traffic Classes, Capacity Protection, and SLOs](https://api7.ai/learning-center/api-gateway-guide/api-gateway-quality-of-service)[46. API Gateway Log Storage: Pipelines, Retention, Security, and Cost](https://api7.ai/learning-center/api-gateway-guide/api-gateway-log-storage)[47. API Gateway Timeouts and Retries: Safe Policies and APISIX Configuration](https://api7.ai/learning-center/api-gateway-guide/api-gateway-timeouts-retries)[48. API Gateway Concurrency Control: Capacity Budgets, Backpressure, and Load Shedding](https://api7.ai/learning-center/api-gateway-guide/api-gateway-concurrency-control)[49. Asynchronous API Gateway Patterns: Queues, Callbacks, and Performance Boundaries](https://api7.ai/learning-center/api-gateway-guide/asynchronous-api-gateway-patterns)[50. API Gateway TLS Performance: Handshakes, Session Reuse, and Measurement](https://api7.ai/learning-center/api-gateway-guide/api-gateway-tls-performance)

06 Gateway Security

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=security)[51. DDoS Defense at the API Gateway: Layered Controls and Failure Planning](https://api7.ai/learning-center/api-gateway-guide/api-gateway-ddos-defense)[52. Distributed API Gateway Rate Limiting: Local vs Redis Counters and Accuracy Trade-offs](https://api7.ai/learning-center/api-gateway-guide/distributed-api-gateway-rate-limiting)[53. API Gateway IP Allowlist and Denylist Management: Trust, Proxies, and Operations](https://api7.ai/learning-center/api-gateway-guide/api-gateway-ip-allowlist-denylist-management)[54. API Gateway Security Scanning: What to Test and How to Operationalize Findings](https://api7.ai/learning-center/api-gateway-guide/api-gateway-security-scanning)[55. SQL Injection and XSS at the API Gateway: Detection Limits and Defense in Depth](https://api7.ai/learning-center/api-gateway-guide/sql-injection-xss-api-gateway)[56. API Access Log Auditing: Evidence, Integrity, Retention, and Review](https://api7.ai/learning-center/api-gateway-guide/api-access-log-auditing)[57. Preventing API Scraping and Abuse: Identity, Behavioral Signals, and Rate Controls](https://api7.ai/learning-center/api-gateway-guide/prevent-api-scraping-abuse)[58. API Gateway mTLS: Client Identity, Certificate Rotation, and APISIX Configuration](https://api7.ai/learning-center/api-gateway-guide/api-gateway-mtls)[59. Fine-Grained API Gateway Authorization: RBAC, ABAC, and External Policy Decisions](https://api7.ai/learning-center/api-gateway-guide/fine-grained-api-gateway-authorization)[60. API Gateway and WAF Reference Architecture: Ownership, Header Trust, and Failure Modes](https://api7.ai/learning-center/api-gateway-guide/api-gateway-waf-reference-architecture)

07 Gateway Ecosystem and Comparisons

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=ecosystem)[61. Apache APISIX vs Kong: Migration, Operations, and Team Fit](https://api7.ai/learning-center/api-gateway-guide/apache-apisix-vs-kong)[62. Traefik vs Kong vs APISIX: A Reproducible API Gateway Benchmark Method](https://api7.ai/learning-center/api-gateway-guide/traefik-kong-apisix-benchmark-method)[63. Amazon API Gateway Explained: Deployment Models, Trade-offs, and Use Cases](https://api7.ai/learning-center/api-gateway-guide/amazon-api-gateway-explained)[64. API Gateway and Istio: Clear North-South and East-West Boundaries](https://api7.ai/learning-center/api-gateway-guide/api-gateway-istio)[65. API Gateway with NGINX: Layering, Ownership, and Migration Patterns](https://api7.ai/learning-center/api-gateway-guide/api-gateway-nginx)[66. API Gateway with Envoy: Deployment Patterns and Policy Ownership](https://api7.ai/learning-center/api-gateway-guide/api-gateway-envoy)[67. API Gateway with Cloudflare API Shield: Edge and Origin Security Boundaries](https://api7.ai/learning-center/api-gateway-guide/api-gateway-cloudflare-api-shield)[68. Apigee vs MuleSoft vs Amazon API Gateway: A Decision Framework](https://api7.ai/learning-center/api-gateway-guide/apigee-mulesoft-amazon-api-gateway)[69. Should an API Gateway Connect Directly to a Database? Patterns and Risks](https://api7.ai/learning-center/api-gateway-guide/api-gateway-database-access-patterns)[70. API Gateway Architecture for Large-Scale SaaS Platforms](https://api7.ai/learning-center/api-gateway-guide/api-gateway-large-scale-saas-architecture)

08 Industry Applications and Integrations

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=applications)[71. API Gateway CI/CD: Validation, Promotion, and Safe Rollback](https://api7.ai/learning-center/api-gateway-guide/api-gateway-ci-cd)[72. API Gateways for AI and ML Inference: Traffic, Security, and Observability](https://api7.ai/learning-center/api-gateway-guide/api-gateways-ai-ml-inference)[73. API Gateway Architecture for Financial Services: Controls and Failure Boundaries](https://api7.ai/learning-center/api-gateway-guide/api-gateway-financial-services)[74. API Gateway Architecture for E-Commerce: Checkout Reliability and Traffic Peaks](https://api7.ai/learning-center/api-gateway-guide/api-gateway-ecommerce)[75. API Gateways for Mobile Applications: Authentication, Payloads, and Versioning](https://api7.ai/learning-center/api-gateway-guide/api-gateways-mobile-applications)[76. API Gateways for Web3 Applications: RPC Traffic, Identity, and Abuse Controls](https://api7.ai/learning-center/api-gateway-guide/api-gateways-web3-applications)[77. OpenAPI-Driven API Gateway Operations: Import, Validation, and Drift Control](https://api7.ai/learning-center/api-gateway-guide/openapi-driven-api-gateway-operations)[78. gRPC-Web and gRPC Transcoding Through an API Gateway](https://api7.ai/learning-center/api-gateway-guide/grpc-web-grpc-transcoding-api-gateway)[79. API Gateway Pricing and Cost Optimization: A Workload-Based Model](https://api7.ai/learning-center/api-gateway-guide/api-gateway-pricing-cost-optimization)[80. Evaluating API Gateway Directions: Evidence and Architectural Impact](https://api7.ai/learning-center/api-gateway-guide/api-gateway-trends)

09 Advanced Gateway Applications

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=operations)[81. API Gateways in Zero Trust Architecture: Identity, Policy, and Limits](https://api7.ai/learning-center/api-gateway-guide/api-gateways-zero-trust-architecture)[82. API Gateway Log Analytics: Correlation, Queries, and Operational Signals](https://api7.ai/learning-center/api-gateway-guide/api-gateway-log-analytics)[83. From API Sprawl to Governed Delivery: The Gateway's Role in Modernization](https://api7.ai/learning-center/api-gateway-guide/api-gateway-modernization)[84. API Monetization at the Gateway: Plans, Metering, Entitlements, and Billing Boundaries](https://api7.ai/learning-center/api-gateway-guide/api-monetization-gateway)[85. Safe AI-Assisted API Gateway Optimization: Recommendations, Guardrails, and Approval](https://api7.ai/learning-center/api-gateway-guide/ai-assisted-api-gateway-optimization)[86. API Gateways for Low-Code and No-Code Integration: Governance and Safety](https://api7.ai/learning-center/api-gateway-guide/api-gateways-low-code-no-code-integration)[87. API Gateway and CIAM Integration: Token Validation, Consent, and Identity Context](https://api7.ai/learning-center/api-gateway-guide/api-gateway-ciam-integration)[88. Elastic API Gateway Scaling: Signals, Capacity, and Safe Scale-In](https://api7.ai/learning-center/api-gateway-guide/elastic-api-gateway-scaling)[89. Multi-Tenant SaaS API Gateways: Isolation, Quotas, and Tenant-Aware Policy](https://api7.ai/learning-center/api-gateway-guide/multi-tenant-saas-api-gateway-policy)[90. API Gateway DevSecOps: Policy as Code, Testing, and Runtime Feedback](https://api7.ai/learning-center/api-gateway-guide/api-gateway-devsecops)

10 Platform Engineering and Planning

[View this topic · 10](https://api7.ai/learning-center/api-gateway-guide?topic=platform-governance)[91. API Discovery and Documentation at the Gateway: Inventory, Ownership, and Drift](https://api7.ai/learning-center/api-gateway-guide/api-discovery-documentation-gateway)[92. WebAssembly Plugins for API Gateways: Portability, Isolation, and APISIX Boundaries](https://api7.ai/learning-center/api-gateway-guide/api-gateway-webassembly-plugins)[93. Monitoring API Gateways with Prometheus and Grafana: Metrics, Dashboards, and Alerts](https://api7.ai/learning-center/api-gateway-guide/monitor-api-gateways-prometheus-grafana)[94. API Gateway Reliability Engineering: SLOs, Failure Isolation, and Incident Response](https://api7.ai/learning-center/api-gateway-guide/api-gateway-reliability-engineering)[95. API Gateways for Edge AI Inference: Routing, Constraints, and Observability](https://api7.ai/learning-center/api-gateway-guide/api-gateways-edge-ai-inference)[96. Reducing Cloud Cost with API Gateway Controls: Measurement Before Optimization](https://api7.ai/learning-center/api-gateway-guide/reducing-cloud-cost-api-gateway-controls)[97. Improving API Developer Experience with Gateway Standards and Self-Service](https://api7.ai/learning-center/api-gateway-guide/improving-api-developer-experience-gateway-self-service)[98. API Gateway Change Management: Compatibility, Progressive Delivery, and Rollback](https://api7.ai/learning-center/api-gateway-guide/api-gateway-change-management-rollback)[99. Operating Serverless APIs: Cold Starts, Idempotency, and Asynchronous Handoffs](https://api7.ai/learning-center/api-gateway-guide/operating-serverless-apis-gateway)[100. Planning an API Gateway Roadmap for the Next Five Years](https://api7.ai/learning-center/api-gateway-guide/planning-api-gateway-roadmap-next-five-years)

[API Gateway Guide](https://api7.ai/learning-center/api-gateway-guide)[Gateway Ecosystem and Comparisons](https://api7.ai/learning-center/api-gateway-guide?topic=ecosystem)

On this page

On this page

- [Key Takeaways](#key-takeaways)

- [Separate Gateway and Data Responsibilities](#separate-gateway-and-data-responsibilities)

- [Why Direct Database Access Becomes Fragile](#why-direct-database-access-becomes-fragile)

  - [Domain Authorization Moves to the Wrong Layer](#domain-authorization-moves-to-the-wrong-layer)
  - [Connections Become Request-Path Capacity](#connections-become-request-path-capacity)
  - [Transactions and Retries Lose Context](#transactions-and-retries-lose-context)
  - [Schema Changes Leak Into the Public Edge](#schema-changes-leak-into-the-public-edge)

- [Choose a Safer Pattern](#choose-a-safer-pattern)

- [Treat Exceptions as Products, Not Shortcuts](#treat-exceptions-as-products-not-shortcuts)

- [Recommended APISIX Boundary](#recommended-apisix-boundary)

- [Production Checklist](#production-checklist)

- [FAQ](#faq)

  - [Can an API gateway technically connect to a database?](#can-an-api-gateway-technically-connect-to-a-database)
  - [Is direct access acceptable for read-only data?](#is-direct-access-acceptable-for-read-only-data)
  - [Does a gateway timeout cancel the database query?](#does-a-gateway-timeout-cancel-the-database-query)

- [Next Steps](#next-steps)

Article 69

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

API7.ai

September 15, 2026

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](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-integration-types.html). Apigee describes a proxy as a facade that forwards to a [TargetEndpoint or backend service](https://cloud.google.com/apigee/docs/api-platform/fundamentals/understanding-apis-and-api-proxies). 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

| Requirement                       | Preferred path                                    | Why                                                              |
| --------------------------------- | ------------------------------------------------- | ---------------------------------------------------------------- |
| Transactional read or write       | Gateway → domain service → database               | Keeps authorization, transactions, and schema ownership together |
| Short serverless operation        | Gateway → function → database                     | Isolates database client and IAM policy from gateway runtime     |
| Long-running or bursty write      | Gateway → service → queue/workflow → worker       | Decouples request admission from processing capacity             |
| Public, read-heavy reference data | Gateway/CDN cache → read API or materialized view | Reduces database load with an explicit staleness contract        |
| Cloud service action              | Supported gateway service integration             | Uses a documented service API and scoped cloud identity          |

The [Amazon API Gateway HTTP API documentation](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html) 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](https://apisix.apache.org/docs/apisix/3.18/plugins/serverless/) 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.

## Recommended APISIX Boundary

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](https://apisix.apache.org/docs/apisix/3.18/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](https://api7.ai/learning-center/api-gateway-guide/api-gateway-timeouts-retries), apply [concurrency budgets and backpressure](https://api7.ai/learning-center/api-gateway-guide/api-gateway-concurrency-control), and define [fine-grained authorization ownership](https://api7.ai/learning-center/api-gateway-guide/fine-grained-api-gateway-authorization) before exposing a data-backed API.

[Previous article**Apigee vs MuleSoft vs Amazon API Gateway: A Decision Framework**](https://api7.ai/learning-center/api-gateway-guide/apigee-mulesoft-amazon-api-gateway)[Next article**API Gateway Architecture for Large-Scale SaaS Platforms**](https://api7.ai/learning-center/api-gateway-guide/api-gateway-large-scale-saas-architecture)

On this page

- [Key Takeaways](#key-takeaways)

- [Separate Gateway and Data Responsibilities](#separate-gateway-and-data-responsibilities)

- [Why Direct Database Access Becomes Fragile](#why-direct-database-access-becomes-fragile)

  - [Domain Authorization Moves to the Wrong Layer](#domain-authorization-moves-to-the-wrong-layer)
  - [Connections Become Request-Path Capacity](#connections-become-request-path-capacity)
  - [Transactions and Retries Lose Context](#transactions-and-retries-lose-context)
  - [Schema Changes Leak Into the Public Edge](#schema-changes-leak-into-the-public-edge)

- [Choose a Safer Pattern](#choose-a-safer-pattern)

- [Treat Exceptions as Products, Not Shortcuts](#treat-exceptions-as-products-not-shortcuts)

- [Recommended APISIX Boundary](#recommended-apisix-boundary)

- [Production Checklist](#production-checklist)

- [FAQ](#faq)

  - [Can an API gateway technically connect to a database?](#can-an-api-gateway-technically-connect-to-a-database)
  - [Is direct access acceptable for read-only data?](#is-direct-access-acceptable-for-read-only-data)
  - [Does a gateway timeout cancel the database query?](#does-a-gateway-timeout-cancel-the-database-query)

- [Next Steps](#next-steps)
