---
# === IDENTITY ===
id: business/erp-integration/api-gateway-patterns-erp/2026
canonical_question: "When should you put an API gateway in front of ERP APIs and when is it overkill?"
aliases:
  - "Do I need an API gateway for ERP integration?"
  - "API gateway vs iPaaS for ERP API management"
  - "Kong vs Apigee vs AWS API Gateway for ERP APIs"
  - "When is an API gateway overkill for ERP integrations?"
entity_type: erp_integration
domain: business > erp-integration > api-gateway-patterns-erp
region: global
jurisdiction: global
temporal_scope: 2024-2026

# === SYSTEM PROFILE ===
systems:
  - name: "Cross-ERP (Pattern-level)"
    vendor: "N/A — architecture pattern"
    version: "N/A"
    edition: "All"
    deployment: "cloud"
    api_surface: "REST, OData, SOAP"
  - name: "Kong Gateway"
    vendor: "Kong Inc."
    version: "3.x"
    edition: "Enterprise & OSS"
    deployment: "cloud"
    api_surface: "REST"
  - name: "Google Apigee"
    vendor: "Google Cloud"
    version: "Apigee X"
    edition: "Standard & Enterprise"
    deployment: "cloud"
    api_surface: "REST"
  - name: "AWS API Gateway"
    vendor: "Amazon Web Services"
    version: "v2 (HTTP API)"
    edition: "REST API & HTTP API"
    deployment: "cloud"
    api_surface: "REST"
  - name: "Azure API Management"
    vendor: "Microsoft"
    version: "2024-05-01"
    edition: "Developer, Basic, Standard, Premium"
    deployment: "cloud"
    api_surface: "REST, SOAP passthrough"
  - name: "SAP API Management"
    vendor: "SAP"
    version: "Integration Suite 2024"
    edition: "Standard"
    deployment: "cloud"
    api_surface: "REST, OData"

# === VERIFICATION ===
last_verified: 2026-03-07
confidence: 0.85
version: 1.0
first_published: 2026-03-07

# === TEMPORAL VALIDITY ===
temporal_validity:
  status: evolving
  last_breaking_change: null
  next_review: 2026-09-03
  change_sensitivity: medium

# === CONSTRAINTS ===
constraints:
  - "API gateway adds 5-50ms latency per request — for sub-100ms ERP API calls this can double response time"
  - "Gateway rate limiting stacks with ERP-native rate limits — you must coordinate or risk double-throttling"
  - "Gateway timeout must be longer than ERP timeout or you get orphaned transactions"
  - "Single-gateway deployment is a single point of failure — all ERP traffic dies if the gateway goes down"
  - "Gateway cannot replace iPaaS data transformation — it handles simple header/query rewrites, not multi-step object mapping"
  - "SAP API Management is OEM Apigee Edge — mixing it with standalone Apigee X creates policy conflicts"
  - "Gateway subscription keys are not a substitute for ERP-native OAuth — you need both layers"

# === SKIP CONDITIONS ===
skip_this_unit_if:
  - condition: "Single integration between two systems with an iPaaS already handling auth, rate limiting, and monitoring"
    use_instead: "business/erp-integration/ipaas-platform-comparison/2026"
  - condition: "Need to choose a specific iPaaS platform"
    use_instead: "business/erp-integration/ipaas-platform-comparison/2026"
  - condition: "Need ERP-specific API capabilities and rate limits"
    use_instead: "business/erp-integration/{system}-rest-api-capabilities/2026"
  - condition: "Internal-only integration with no external API consumers"
    use_instead: "Direct ERP API calls with retry logic — gateway adds unnecessary complexity"

# === AGENT HINTS ===
inputs_needed:
  - key: consumer_count
    question: "How many different applications or teams consume your ERP APIs?"
    type: choice
    options:
      - "1 (single integration)"
      - "2-5 (small team)"
      - "6-20 (department-level)"
      - "> 20 (enterprise-wide or external)"
  - key: erp_systems
    question: "Which ERP system(s) are you exposing APIs for?"
    type: choice
    options:
      - "Salesforce"
      - "SAP S/4HANA"
      - "Oracle ERP Cloud"
      - "Microsoft Dynamics 365"
      - "NetSuite"
      - "Multiple ERPs"
  - key: existing_middleware
    question: "Do you already have an iPaaS or integration platform?"
    type: choice
    options:
      - "Yes — MuleSoft, Boomi, Workato, Celigo, or similar"
      - "Yes — SAP Integration Suite / BTP"
      - "Yes — Azure Integration Services"
      - "No — direct API calls only"

# === DISTRIBUTION ===
canonical_source: "https://knowledgelib.io/business/erp-integration/api-gateway-patterns-erp/2026"
suggested_citation: "Source: knowledgelib.io — AI Knowledge Library (verified 2026-03-07)"

# === RELATED UNITS ===
related_kos:
  depends_on:
    - id: "business/erp-integration/erp-rate-limits-comparison/2026"
      label: "ERP Rate Limits Comparison — understand native limits before adding gateway limits"
  related_to:
    - id: "business/erp-integration/ipaas-platform-comparison/2026"
      label: "iPaaS Platform Comparison — when iPaaS handles gateway concerns"
    - id: "business/erp-integration/erp-authentication-comparison/2026"
      label: "ERP Authentication Comparison — auth flows the gateway must support"
    - id: "business/erp-integration/error-handling-dead-letter-queues/2026"
      label: "Error Handling & Dead Letter Queues — gateway-level circuit breakers"
  alternative_to:
    - id: "business/erp-integration/sap-btp-integration-vs-standalone-ipaas/2026"
      label: "SAP BTP Integration Suite vs Standalone iPaaS — SAP's built-in API management"
  often_confused_with:
    - id: "business/erp-integration/mulesoft-anypoint-capabilities/2026"
      label: "MuleSoft Anypoint — iPaaS with built-in API gateway (not a standalone gateway)"

# === SOURCES ===
sources:
  - id: src1
    title: "How to Choose the Right API Gateway for Your Platform"
    author: Moesif
    url: https://www.moesif.com/blog/technical/api-gateways/How-to-Choose-The-Right-API-Gateway-For-Your-Platform-Comparison-Of-Kong-Tyk-Apigee-And-Alternatives/
    type: technical_blog
    published: 2025-06-15
    reliability: high
  - id: src2
    title: "API Gateway: Why It Quietly Becomes the Single Point of Failure"
    author: Umut Akbulut
    url: https://medium.com/@umutt.akbulut/api-gateway-why-it-quietly-becomes-the-single-point-of-failure-in-modern-enterprises-the-paradox-26332585b002
    type: technical_blog
    published: 2025-12-10
    reliability: moderate_high
  - id: src3
    title: "D365 F&O/Commerce Interfacing via Azure API Management: Best Practices"
    author: Patrick Mouwen
    url: https://patrickmouwen.com/d365-technical/my-best-practices-for-d365fo-d365commerce-interfacing-via-apim/
    type: technical_blog
    published: 2025-03-22
    reliability: high
  - id: src4
    title: "Integration Platform as a Service (iPaaS) vs API Management: Why You Need Both"
    author: Workato
    url: https://www.workato.com/the-connector/api-management-integration-unified/
    type: industry_report
    published: 2025-08-14
    reliability: moderate_high
  - id: src5
    title: "SAP API Management — Integration Suite on SAP BTP"
    author: SAP
    url: https://help.sap.com/docs/integration-suite/sap-integration-suite/api-management-capability
    type: official_docs
    published: 2025-12-08
    reliability: authoritative
  - id: src6
    title: "Changing Views on Integration — ESB to API Gateway, Serverless, and iPaaS"
    author: AMIS Technology Blog
    url: https://technology.amis.nl/architecture/changing-views-on-integration-from-enterprise-service-bus-to-api-gateway-serverless-and-ipaas/
    type: technical_blog
    published: 2024-09-15
    reliability: high
  - id: src7
    title: "API Rate Limiting at Scale: Patterns, Failures, and Control Strategies"
    author: Gravitee
    url: https://www.gravitee.io/blog/rate-limiting-apis-scale-patterns-strategies
    type: technical_blog
    published: 2025-11-20
    reliability: high
  - id: src8
    title: "Throttle Requests to Your REST APIs for Better Throughput in API Gateway"
    author: Amazon Web Services
    url: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html
    type: official_docs
    published: 2025-10-01
    reliability: authoritative
---

# API Gateway Patterns for ERP Integration: When to Use and When It's Overkill

## TL;DR

- **Bottom line**: Put an API gateway in front of ERP APIs when you have 5+ consumers, need unified auth/rate limiting across multiple ERPs, or must expose ERP data to external parties. Skip it when your iPaaS already handles these concerns or you have a single point-to-point integration.
- **Key limit**: Gateway adds 5-50ms latency per hop and introduces a single point of failure unless deployed in HA mode — for internal-only integrations this overhead often exceeds the benefit.
- **Watch out for**: Double rate limiting — gateway rate limits stack with ERP-native limits (e.g., Salesforce 100K/24h, D365 6,000/5min), and the stricter one silently wins, confusing debugging.
- **Best for**: Centralized API management when 6+ applications consume ERP APIs, external partner access to ERP data, or multi-ERP environments needing unified monitoring.
- **Authentication**: Gateway handles consumer-facing auth (API keys, OAuth client credentials) but must still authenticate to each ERP using ERP-native OAuth/TBA — two auth layers, not one.

## System Profile

This card covers the architecture pattern of placing an API gateway between API consumers and ERP backend systems. It is system-agnostic and applies to any ERP (Salesforce, SAP S/4HANA, Oracle ERP Cloud, Dynamics 365, NetSuite, Workday) with any gateway product (Kong, Apigee, AWS API Gateway, Azure APIM, SAP API Management). The card does NOT cover iPaaS-specific API management features (MuleSoft API Manager, Boomi API Management) — those are covered in the iPaaS comparison card.

| System | Role | API Surface | Direction |
|---|---|---|---|
| API Gateway (Kong / Apigee / AWS / Azure APIM / SAP) | Proxy, auth, rate limiting, monitoring | REST, OData passthrough | Inbound from consumers |
| ERP System(s) | Backend data source / target | REST, OData, SOAP, Bulk | Outbound to consumers via gateway |
| iPaaS (optional) | Data transformation, orchestration | N/A | Between gateway and ERP |
| API Consumers | Applications, partners, agents | REST (via gateway) | Inbound |

## API Surfaces & Capabilities

This section compares what each gateway product offers for ERP API proxying.

| Gateway | Deployment | Rate Limiting | Request Transform | Auth Methods | Circuit Breaker | Analytics | Pricing Model |
|---|---|---|---|---|---|---|---|
| Kong Gateway 3.x | Self-hosted, Konnect Cloud | Sliding window, fixed window, local/cluster | Headers, query params, body (with plugins) | OAuth 2.0, JWT, API key, mTLS, LDAP | Yes (plugin) | Prometheus, Datadog, custom | OSS free; Enterprise ~$50K+/yr |
| Google Apigee X | Google Cloud managed | Spike arrest, quota, concurrent rate limit | AssignMessage, JavaScript, XSLT policies | OAuth 2.0, API key, SAML, JWT | Yes (via target server health) | Built-in analytics dashboard | Pay-per-use or committed ($$$) |
| AWS API Gateway v2 | AWS managed | 10,000 RPS default (adjustable), per-route throttle | VTL mapping templates (REST API), Lambda transform | IAM, Cognito, Lambda authorizer, API key | No native (use Lambda or Step Functions) | CloudWatch metrics, access logs | $1.00-$3.50 per million requests |
| Azure API Management | Azure managed, self-hosted gateway option | Rate limit by key, IP, subscription, custom | Inbound/outbound/backend policies (Liquid, XSLT) | OAuth 2.0, certificates, subscription keys, managed identity | Yes (via backend policy retry/circuit) | Application Insights, built-in analytics | Developer free; Standard ~$700/mo; Premium ~$2,800/mo |
| SAP API Management | SAP BTP managed (OEM Apigee Edge) | Spike arrest, quota (Apigee policies) | AssignMessage, JavaScript, KVM | OAuth 2.0, API key, SAML, principal propagation | Yes (via Apigee target health) | Built-in + SAP Analytics Cloud | Bundled with Integration Suite license |
| MuleSoft API Manager | Anypoint Platform (iPaaS + gateway) | Rate limit, spike control, SLA-based tiers | Full DataWeave transformation (iPaaS-grade) | OAuth 2.0, client ID enforcement, JWT, LDAP | Yes (built-in) | Anypoint Monitoring, Visualizer | Bundled with Anypoint license ($$$) |

[src1, src5]

## Rate Limits & Quotas

### Gateway vs ERP Rate Limits — The Coordination Problem

The critical challenge is that gateway rate limits and ERP-native rate limits operate independently. You must configure gateway limits to be stricter than ERP limits, or consumers hit opaque ERP errors instead of clean gateway 429 responses.

| ERP System | Native Rate Limit | Window | Gateway Should Be Set To |
|---|---|---|---|
| Salesforce | 100,000 API calls (Enterprise) | 24h rolling | < 90,000/24h (10% safety margin) |
| SAP S/4HANA Cloud | Fair-use throttling (no hard number) | Per-request | Monitor and adapt — no fixed target |
| Oracle ERP Cloud | Throttled at service level | Per-request | Conservative — start at 60 req/min |
| Dynamics 365 (Dataverse) | 6,000 requests per 5 min per user | 5 min rolling | < 5,000/5min per user with burst allowance |
| NetSuite (SuiteTalk) | 10 concurrent requests, governance units | Per-script execution | < 8 concurrent, match governance budget |
| Workday | No published hard limits (fair-use) | N/A | Start at 120 req/min, adjust based on 429s |

[src7, src8]

### Per-Request Limits at the Gateway

| Limit Type | Kong | Apigee | AWS API Gateway | Azure APIM |
|---|---|---|---|---|
| Max request body size | Configurable (default 8MB) | 10 MB (default) | 10 MB (REST), 10 MB (HTTP) | 256 KB - 4 MB (by tier) |
| Max response size | Configurable | 10 MB | 10 MB | Same as request |
| Request timeout | Configurable (default 60s) | 55s (default, configurable) | 29s (hard limit for REST API) | 240s (configurable) |
| Max header size | 64 KB (default) | 25 headers / 7 KB each | 10,240 bytes total | 32 KB |
| WebSocket support | Yes (Enterprise) | No | Yes (HTTP API) | Yes (Premium tier) |

[src1, src8]

## Authentication

### Two-Layer Auth Model

An API gateway in front of ERP APIs creates a two-layer authentication architecture. The gateway authenticates the consumer; the gateway itself authenticates to the ERP.

| Layer | Who Authenticates | Flow | Token Lifetime | Managed By |
|---|---|---|---|---|
| Consumer-to-Gateway | API consumer (app, partner, agent) | API key, OAuth 2.0 client credentials, JWT | Minutes to hours | Gateway admin |
| Gateway-to-ERP | Gateway service account | ERP-native OAuth 2.0, TBA, certificate, principal propagation | Session-based (hours) | ERP admin |

[src1, src3]

### Per-ERP Gateway Authentication

| ERP | Recommended Gateway-to-ERP Auth | Gotcha |
|---|---|---|
| Salesforce | OAuth 2.0 JWT Bearer (server-to-server) | Connected app digital certificate required; gateway must cache and refresh tokens |
| SAP S/4HANA | OAuth 2.0 client credentials via BTP or SAML2 Bearer | Principal propagation needed if ERP authorization is user-based — gateway must forward user context |
| Oracle ERP Cloud | OAuth 2.0 client credentials | Token refresh endpoint differs from authorization endpoint — don't hardcode |
| Dynamics 365 | Azure AD client credentials (managed identity if Azure APIM) | Azure APIM + managed identity = zero-secret setup; non-Azure gateways need client secret rotation |
| NetSuite | Token-Based Authentication (TBA) | TBA tokens don't expire but are per-integration; Kong/Apigee need custom plugin for HMAC-SHA256 signing |

[src3]

### Authentication Gotchas

- Gateway API keys give a false sense of security — they protect the gateway, not the ERP. A leaked API key with cached ERP tokens = full ERP access. [src1]
- Azure APIM with managed identity to Dynamics 365 is the only zero-secret gateway-to-ERP pattern. All others require secret rotation. [src3]
- SAP API Management uses principal propagation to forward user identity through the gateway to S/4HANA — third-party gateways cannot replicate this without custom SAML assertion injection. [src5]

## Constraints
<!-- Agents: read this section before recommending any integration approach from this unit.
     These are hard constraints that must not be violated. -->

- Gateway rate limits stack with ERP-native rate limits — you must set gateway limits below ERP limits or debugging becomes impossible
- AWS API Gateway has a hard 29-second timeout on REST APIs — ERP bulk operations that take longer will be cut off (use HTTP API type or ALB instead)
- Gateway cannot replace iPaaS transformation logic — it handles header/query rewriting but not multi-object data mapping between ERP schemas
- SAP API Management is built on OEM Apigee Edge (not Apigee X) — policies may differ from current Apigee X documentation
- Single-region gateway deployment means all ERP traffic routes through one region — add latency for global ERP deployments
- Gateway subscription keys + ERP OAuth = two auth layers, not one — consumers must manage both unless the gateway fully abstracts ERP auth

## Integration Pattern Decision Tree

```
START — Should I put an API gateway in front of my ERP APIs?
├── How many applications/teams consume ERP APIs?
│   ├── 1 (single integration)
│   │   ├── Using iPaaS (MuleSoft, Boomi, etc.)?
│   │   │   ├── YES → SKIP GATEWAY — iPaaS handles auth, rate limiting, monitoring
│   │   │   └── NO → SKIP GATEWAY — direct API with retry logic is simpler
│   │   └── Need external partner access?
│   │       ├── YES → ADD GATEWAY — security boundary for external consumers
│   │       └── NO → SKIP GATEWAY
│   ├── 2-5 consumers
│   │   ├── All internal applications?
│   │   │   ├── YES → MAYBE — gateway adds value if you need unified monitoring/auth
│   │   │   └── NO (external partners) → ADD GATEWAY — security + rate limiting per partner
│   │   └── iPaaS already managing these connections?
│   │       ├── YES → CHECK iPaaS API management features first
│   │       └── NO → ADD GATEWAY — prevents N x M credential sprawl
│   └── 6+ consumers or external API program
│       └── ADD GATEWAY — this is the sweet spot for API management
├── Which ERP?
│   ├── Salesforce → Gateway adds value for auth consolidation; rate limiting is secondary (SF already enforces)
│   ├── SAP S/4HANA on BTP → USE SAP API MANAGEMENT — native integration, principal propagation
│   ├── SAP S/4HANA on-premise → ADD GATEWAY — SAP API Management or Kong as reverse proxy
│   ├── Dynamics 365 → USE AZURE APIM — managed identity, zero-secret auth, native fit
│   ├── Oracle ERP Cloud → ADD GATEWAY — Oracle doesn't have equivalent built-in API management
│   └── NetSuite → ADD GATEWAY only if >5 consumers — TBA is complex enough without adding gateway auth
├── What does the gateway need to do?
│   ├── Rate limiting only → CHECK if ERP native limits are sufficient first
│   ├── Auth consolidation → ADD GATEWAY — single API key for consumers, gateway handles ERP OAuth
│   ├── Request transformation → SIMPLE (header/query rewrite) → gateway OK
│   │                          → COMPLEX (object mapping) → USE iPaaS instead
│   ├── Monitoring/analytics → ADD GATEWAY — unified observability across all ERP APIs
│   ├── API versioning → ADD GATEWAY — proxy old paths to new ERP API versions
│   └── Caching → ADD GATEWAY — cache reference data (product catalog, org structure)
└── What's the deployment constraint?
    ├── Single cloud (AWS) → AWS API Gateway or Kong on EKS
    ├── Single cloud (Azure) → Azure APIM (especially for D365)
    ├── Single cloud (GCP) → Apigee X
    ├── SAP BTP → SAP API Management
    ├── Multi-cloud → Kong (cloud-agnostic) or Apigee (runs on Anthos)
    └── On-premise ERP → Kong (self-hosted) or Azure APIM self-hosted gateway
```

## Quick Reference

### Gateway Product Decision Matrix

| Criterion | Kong | Apigee X | AWS API Gateway | Azure APIM | SAP API Mgmt |
|---|---|---|---|---|---|
| Best for ERP | Multi-cloud, on-prem SAP | Multi-ERP, analytics-heavy | AWS-native workloads | Dynamics 365 | SAP S/4HANA on BTP |
| Rate limiting | Sliding/fixed window, cluster-wide | Spike arrest + quota + concurrent | Per-route throttle, 10K RPS default | Per-key, per-IP, per-subscription | Spike arrest + quota (Apigee Edge) |
| Request transform | Plugin-based (body, headers, query) | AssignMessage + JavaScript policies | VTL templates (limited) | Liquid + XSLT policies | AssignMessage + JavaScript |
| Circuit breaker | Yes (plugin) | Via target server health checks | No native | Via backend policy | Via Apigee target health |
| Developer portal | Yes (Enterprise) | Yes (built-in) | No (use third-party) | Yes (built-in) | Yes (API Business Hub Enterprise) |
| mTLS support | Yes | Yes | Yes (mutual TLS) | Yes | Yes |
| Multi-region | Manual (deploy per region) | Global (Anthos) | Per-region, multi-region via CloudFront | Premium tier (multi-region) | Single BTP subaccount region |
| OSS option | Yes (Kong OSS) | No | No | No | No |
| ERP-specific connectors | No (generic proxy) | No (generic proxy) | No (generic proxy) | D365 connector in Logic Apps | SAP system prebuilt adapters |
| Typical cost (mid-scale) | OSS free; Enterprise $50K+/yr | $25K-$100K+/yr | $1-3.50 per million requests | $700-$2,800/mo by tier | Bundled with IS license |

[src1, src5, src8]

## Step-by-Step Integration Guide

### 1. Assess whether a gateway is needed

Before deploying a gateway, audit your current ERP API landscape. Count consumers, map authentication flows, and check if your iPaaS already provides API management. [src6]

```bash
# Audit checklist — answer these before choosing a gateway
# 1. How many applications call ERP APIs? → If < 5 and all internal, gateway may be overkill
# 2. Do external partners need ERP data? → If yes, gateway is mandatory
# 3. Does your iPaaS have API management? → MuleSoft API Manager, Boomi API Mgmt, SAP API Mgmt
# 4. Which ERP systems are involved? → D365 = Azure APIM; SAP BTP = SAP API Mgmt
# 5. What's your timeout requirement? → AWS API GW hard limit is 29s (REST API type)
```

**Verify**: If you answered "< 5 internal consumers" and "iPaaS handles auth/rate limiting" → skip the gateway.

### 2. Configure gateway-to-ERP authentication

The gateway must authenticate to each ERP system using ERP-native credentials. This is the most error-prone step. [src3]

```yaml
# Kong declarative config — Salesforce OAuth 2.0 JWT Bearer
# File: kong.yml
services:
  - name: salesforce-api
    url: https://your-instance.salesforce.com
    routes:
      - name: salesforce-query
        paths:
          - /erp/salesforce
    plugins:
      - name: oauth2-introspection
        config:
          introspection_url: https://login.salesforce.com/services/oauth2/introspect
      - name: request-transformer
        config:
          add:
            headers:
              - "Authorization: Bearer $(cached_sf_token)"
```

**Verify**: `curl -H "apikey: YOUR_KEY" https://gateway.example.com/erp/salesforce/services/data/v62.0/limits` → returns Salesforce API limits JSON.

### 3. Set rate limits below ERP native limits

Configure gateway rate limiting with a 10-15% safety margin below ERP native limits. This ensures consumers get clean 429 responses from the gateway instead of opaque errors from the ERP. [src7]

```yaml
# Kong rate-limiting plugin — Salesforce example
plugins:
  - name: rate-limiting
    service: salesforce-api
    config:
      # Salesforce Enterprise: 100,000/24h = ~69/min average
      # Set gateway to 60/min with burst allowance
      minute: 60
      hour: 3500
      day: 85000        # 85K gateway limit vs 100K SF limit = 15% margin
      policy: cluster   # Important: use cluster-wide counter, not per-node
      fault_tolerant: true
      hide_client_headers: false  # Let consumers see X-RateLimit headers
```

**Verify**: Send 65 requests in 1 minute → requests 61-65 return HTTP 429 with `Retry-After` header.

### 4. Configure circuit breaker for ERP backend

ERP systems have maintenance windows and occasional slowdowns. A circuit breaker at the gateway prevents cascading failures. [src2]

```yaml
# Kong circuit breaker (via upstream health checks)
upstreams:
  - name: salesforce-upstream
    targets:
      - target: your-instance.salesforce.com:443
    healthchecks:
      active:
        https_verify_certificate: true
        healthy:
          interval: 10          # Check every 10 seconds
          successes: 3          # 3 successes to mark healthy
        unhealthy:
          interval: 5           # Check every 5 seconds when unhealthy
          tcp_failures: 3       # 3 TCP failures to mark unhealthy
          timeouts: 3           # 3 timeouts to mark unhealthy
          http_failures: 3      # 3 HTTP 5xx to mark unhealthy
      passive:
        unhealthy:
          tcp_failures: 3
          timeouts: 3
          http_failures: 3
```

**Verify**: Simulate ERP downtime → gateway returns 503 after threshold, stops sending requests, auto-recovers when ERP comes back.

## Code Examples

### Python: Gateway rate limit coordination checker

```python
# Input:  ERP rate limit config, gateway rate limit config
# Output: Validation result — are gateway limits safely below ERP limits

def validate_rate_limits(erp_limits: dict, gateway_limits: dict, margin: float = 0.15):
    """Ensure gateway rate limits are set below ERP native limits with safety margin."""
    issues = []
    for window, erp_limit in erp_limits.items():
        gw_limit = gateway_limits.get(window)
        if gw_limit is None:
            issues.append(f"WARNING: No gateway {window} limit set — ERP will enforce at {erp_limit}")
            continue
        max_safe = int(erp_limit * (1 - margin))
        if gw_limit > max_safe:
            issues.append(
                f"DANGER: Gateway {window} limit ({gw_limit}) exceeds safe threshold "
                f"({max_safe}) for ERP limit ({erp_limit}). "
                f"Set gateway to <= {max_safe}."
            )
        else:
            issues.append(f"OK: Gateway {window} limit ({gw_limit}) safely below ERP ({erp_limit})")
    return issues

# Example: Salesforce Enterprise
sf_limits = {"daily": 100_000, "hourly": 5_000}
gw_limits = {"daily": 85_000, "hourly": 4_250}
for line in validate_rate_limits(sf_limits, gw_limits):
    print(line)
# OK: Gateway daily limit (85000) safely below ERP (100000)
# OK: Gateway hourly limit (4250) safely below ERP (5000)
```

### YAML: Azure APIM policy for Dynamics 365

```xml
<!-- Azure APIM inbound policy — Dynamics 365 Dataverse proxy -->
<!-- Input:  Consumer request with subscription key -->
<!-- Output: Proxied request to Dataverse with Azure AD token -->

<policies>
  <inbound>
    <!-- Rate limit: D365 allows 6,000/5min per user -->
    <rate-limit-by-key
      calls="5000"
      renewal-period="300"
      counter-key="@(context.Subscription.Id)"
      increment-condition="@(context.Response.StatusCode >= 200)" />

    <!-- Get Azure AD token using managed identity (zero secrets!) -->
    <authentication-managed-identity
      resource="https://your-org.crm.dynamics.com" />

    <!-- Transform consumer-friendly path to Dataverse OData -->
    <rewrite-uri template="/api/data/v9.2/{remaining}" />

    <set-header name="OData-MaxVersion" exists-action="override">
      <value>4.0</value>
    </set-header>
    <set-header name="Prefer" exists-action="override">
      <value>odata.include-annotations="*"</value>
    </set-header>
  </inbound>
  <backend>
    <forward-request timeout="120" />
  </backend>
  <outbound>
    <!-- Strip internal D365 headers from consumer response -->
    <set-header name="x-ms-dynamics-entity" exists-action="delete" />
  </outbound>
  <on-error>
    <choose>
      <when condition="@(context.Response.StatusCode == 429)">
        <!-- D365 rate limited — return clean error to consumer -->
        <return-response>
          <set-status code="429" reason="Rate limit exceeded" />
          <set-header name="Retry-After" exists-action="override">
            <value>60</value>
          </set-header>
        </return-response>
      </when>
    </choose>
  </on-error>
</policies>
```

### cURL: Test gateway-proxied ERP API

```bash
# Input:  Gateway URL, API key
# Output: ERP data via gateway proxy

# Test Salesforce query through Kong gateway
curl -s -w "\nHTTP Status: %{http_code}\nTime: %{time_total}s\n" \
  -H "apikey: YOUR_GATEWAY_KEY" \
  "https://gateway.example.com/erp/salesforce/services/data/v62.0/query?q=SELECT+Id,Name+FROM+Account+LIMIT+5"

# Check rate limit headers
curl -s -D - -o /dev/null \
  -H "apikey: YOUR_GATEWAY_KEY" \
  "https://gateway.example.com/erp/salesforce/services/data/v62.0/limits" \
  | grep -i "x-ratelimit"
# X-RateLimit-Limit-Minute: 60
# X-RateLimit-Remaining-Minute: 59
```

## Data Mapping

### Gateway Responsibility vs iPaaS Responsibility

| Concern | Gateway Can Handle | iPaaS Should Handle | Notes |
|---|---|---|---|
| Header injection (auth tokens) | Yes | Yes | Gateway is simpler for this |
| Query parameter rewriting | Yes | Yes | Gateway is simpler |
| URL path transformation | Yes | Yes | Gateway is simpler |
| JSON field renaming (flat) | Possible (with plugins/policies) | Yes | Gateway is fragile for this |
| Object nesting/flattening | No (use iPaaS) | Yes | Beyond gateway scope |
| Multi-object JOIN across ERPs | No | Yes | iPaaS core capability |
| Data type conversion | No (use iPaaS) | Yes | Currency, dates, enums |
| Error response normalization | Yes | Yes | Gateway is ideal for this |
| Response caching | Yes | Possible | Gateway is ideal for this |
| Request/response logging | Yes | Yes | Gateway provides unified view |

### Data Type Gotchas

- Gateway caching of ERP responses can serve stale data — set `Cache-Control: max-age` based on data volatility (product catalog: 3600s, order status: 0s). [src1]
- Gateway request body size limits (10MB on Apigee/AWS) may be smaller than ERP bulk API limits (150MB Salesforce Bulk API) — bulk operations must bypass the gateway. [src8]
- SAP OData `$batch` requests are multipart MIME — some gateways parse these incorrectly, corrupting changeset boundaries. [src5]

## Error Handling & Failure Points

### Common Error Codes

| Code | Gateway vs ERP | Meaning | Cause | Resolution |
|---|---|---|---|---|
| 429 (from gateway) | Gateway | Consumer exceeded gateway rate limit | Too many requests in window | Wait for `Retry-After` header value |
| 429 (from ERP, via gateway) | ERP (passed through) | Consumer exceeded ERP native rate limit | Gateway limit set too high | Reduce gateway rate limit to below ERP limit |
| 502 Bad Gateway | Gateway | ERP returned invalid response | ERP downtime, network error, TLS mismatch | Check ERP health; verify TLS cert not expired |
| 503 Service Unavailable | Gateway | Circuit breaker open or gateway overloaded | Repeated ERP failures tripped circuit breaker | Wait for circuit breaker half-open; check ERP |
| 504 Gateway Timeout | Gateway | ERP response exceeded gateway timeout | ERP slow (maintenance, heavy query) | Increase gateway timeout (but not above ERP timeout) |
| 401 from gateway | Gateway | Invalid or expired consumer API key | Consumer credential issue | Rotate consumer key; check key expiry policy |
| 401 from ERP (via 502) | ERP | Gateway's ERP OAuth token expired | Token cache stale or refresh failed | Check gateway token cache; refresh ERP OAuth token |

[src2, src7]

### Failure Points in Production

- **Gateway timeout < ERP timeout = orphaned transactions**: If the gateway times out at 30s but the ERP operation takes 45s, the consumer sees a 504 but the ERP completes the write. Fix: `Set gateway timeout = ERP timeout + 5s buffer; use idempotency keys for writes`. [src2]
- **Circuit breaker false positive on ERP maintenance**: Scheduled ERP maintenance triggers the circuit breaker, which stays open even after maintenance ends if passive health checks are the only mechanism. Fix: `Always configure active health checks alongside passive; set recovery interval to match ERP maintenance window`. [src2]
- **TLS certificate rotation breaks gateway-to-ERP**: ERP TLS certificate is rotated (especially Salesforce quarterly cert rotation), but gateway trusts the old cert. Fix: `Use CA-bundle trust, not certificate pinning; monitor cert expiry with 30-day alerts`. [src3]
- **Stale cached ERP tokens after ERP password reset**: Admin resets ERP integration user password; gateway continues using cached OAuth token until it expires. Fix: `Implement token refresh on 401; don't cache tokens longer than 1 hour`. [src3]
- **Gateway session affinity conflicts with ERP load balancing**: Some gateways pin sessions to a specific ERP node, defeating ERP-side load balancing. Fix: `Disable session affinity unless ERP explicitly requires it (e.g., SAP stateful RFC sessions)`. [src5]

## Anti-Patterns

### Wrong: Using the API gateway as an integration platform

```yaml
# BAD — treating the gateway like an ESB/iPaaS
# This Kong config tries to do data transformation, orchestration, and business logic
plugins:
  - name: serverless-functions
    config:
      functions:
        # 200 lines of Lua code that:
        # 1. Queries Salesforce for account
        # 2. Queries SAP for open orders
        # 3. Joins the data
        # 4. Transforms to unified schema
        # 5. Applies business rules
        # Result: unmaintainable, untestable, no error recovery
```

### Correct: Gateway does routing and security; iPaaS does transformation

```yaml
# GOOD — gateway handles proxy, auth, rate limiting only
# iPaaS (MuleSoft/Boomi/Workato) handles transformation and orchestration
services:
  - name: order-integration-api
    url: https://mulesoft.example.com/api/v1/orders  # Points to iPaaS, not directly to ERP
    routes:
      - paths: ["/api/orders"]
    plugins:
      - name: rate-limiting
        config: { minute: 60 }
      - name: key-auth
        config: { key_names: ["apikey"] }
# iPaaS internally handles: Salesforce query → SAP order create → response mapping
```

### Wrong: Double rate limiting without coordination

```yaml
# BAD — gateway AND iPaaS AND ERP all enforce separate rate limits
# Consumer gets inconsistent errors from different layers
# Gateway: 100 req/min
# MuleSoft policy: 80 req/min (consumer doesn't know this exists)
# Salesforce: 100K/24h (consumer doesn't know current consumption)
# Result: consumer sees 429 from different sources with different Retry-After values
```

### Correct: Single rate limiting layer with ERP-aware limits

```yaml
# GOOD — gateway is the ONLY consumer-facing rate limiter
# iPaaS rate limiting disabled (or set very high as safety net)
# Gateway limits set 15% below ERP limits
plugins:
  - name: rate-limiting
    config:
      day: 85000     # 15% below Salesforce 100K/24h
      minute: 60     # Burst control
      policy: cluster
      hide_client_headers: false  # Consumers see remaining quota
# iPaaS: rate limiting DISABLED (gateway handles this)
# ERP: native limits are the backstop, never the primary control
```

### Wrong: Gateway as single point of failure

```yaml
# BAD — single gateway instance, no failover
# If this Kong node dies, ALL ERP traffic stops
services:
  - name: all-erp-traffic
    url: https://erp-backend.internal
# Single node, no health checks, no failover
# One process crash = entire company loses ERP API access
```

### Correct: HA gateway with graceful degradation

```yaml
# GOOD — multi-node gateway with direct-to-ERP fallback
# Kong deployed as 3-node cluster behind load balancer
# Application has fallback: gateway unavailable → direct ERP API call
upstreams:
  - name: erp-backend
    targets:
      - target: erp-node-1:443
        weight: 100
      - target: erp-node-2:443
        weight: 100
    healthchecks:
      active:
        healthy: { interval: 5, successes: 2 }
        unhealthy: { interval: 2, tcp_failures: 2, timeouts: 2 }
# Application code: try gateway first, fall back to direct ERP API if 503
```

## Common Pitfalls

- **Pitfall: Treating gateway timeout as ERP timeout**: Gateway timeout (e.g., AWS 29s hard limit) is independent of ERP operation timeout. A bulk import that takes 60s will succeed on the ERP but the consumer gets a 504. Fix: `Use async patterns (return 202 Accepted + polling endpoint) for long-running ERP operations`. [src8]
- **Pitfall: Adding a gateway to a single iPaaS integration**: If MuleSoft or Boomi already handles auth, rate limiting, and monitoring for your one integration, adding a gateway doubles infrastructure cost and adds latency for no benefit. Fix: `Use iPaaS built-in API management features first; add gateway only when consumer count exceeds iPaaS API management capacity`. [src4]
- **Pitfall: Caching ERP write responses**: Gateway caches a POST/PUT response, so subsequent identical requests get the cached "success" response without reaching the ERP — no data is actually written. Fix: `NEVER cache POST/PUT/PATCH/DELETE responses; only cache GET responses for reference data`. [src1]
- **Pitfall: Gateway logs contain ERP credentials**: Request/response logging at the gateway may capture OAuth tokens, API keys, or session IDs in clear text. Fix: `Configure gateway to redact Authorization headers and token fields from logs; use log masking policies`. [src7]
- **Pitfall: Mixing SAP API Management with third-party gateway**: SAP API Management (OEM Apigee Edge) and a standalone Kong/Apigee X create two competing API management layers with conflicting policies. Fix: `Pick one: SAP API Management for SAP-centric landscapes, or a third-party gateway for multi-ERP — never both on the same API path`. [src5]
- **Pitfall: Not handling ERP pagination through the gateway**: ERP APIs return paginated responses (Salesforce nextRecordsUrl, D365 @odata.nextLink). If the gateway rewrites URLs, pagination links break. Fix: `Preserve ERP pagination URLs in response rewriting rules; test pagination end-to-end through the gateway`. [src3]

## Diagnostic Commands

```bash
# Check gateway health and upstream ERP status (Kong)
curl -s http://localhost:8001/upstreams/salesforce-upstream/health | jq '.data[].health'

# Check current rate limit counters (Kong)
curl -s http://localhost:8001/plugins | jq '.data[] | select(.name=="rate-limiting") | .config'

# Test gateway-to-ERP latency (added latency = gateway overhead)
# Direct to ERP:
time curl -s -o /dev/null -w "%{time_total}" https://your-instance.salesforce.com/services/data/v62.0/limits
# Through gateway:
time curl -s -o /dev/null -w "%{time_total}" -H "apikey: KEY" https://gateway.example.com/erp/salesforce/limits
# Difference = gateway overhead (should be < 50ms)

# Check Azure APIM metrics for D365 backend
az apim api show --resource-group RG --service-name APIM --api-id dynamics365 --output table

# Verify gateway TLS cert is not expired (prevents silent ERP connection failures)
echo | openssl s_client -connect gateway.example.com:443 2>/dev/null | openssl x509 -noout -dates

# Check Apigee rate limit quota consumption
curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  "https://apigee.googleapis.com/v1/organizations/ORG/environments/ENV/stats/apiproxy?select=sum(rate_limit.count)"
```

## Version History & Compatibility

| Gateway | Latest Version | Release | Notable Changes | ERP Impact |
|---|---|---|---|---|
| Kong 3.9 | 2025-12 | Current | Improved WebSocket support, new rate-limiting algorithm | Better for event-driven ERP integrations |
| Kong 3.7 | 2025-06 | Supported | AI Gateway plugins | Enables LLM-powered ERP API transformations |
| Apigee X | 2025-Q4 | Current | Advanced security analytics | Better visibility into ERP API abuse |
| AWS API Gateway v2 | 2024-11 | Current | HTTP API type matured | Higher timeout (30min) than REST API (29s) |
| Azure APIM | 2024-05-01 API | Current | Self-hosted gateway v2, managed identity improvements | Better D365 integration with zero-secret auth |
| SAP API Management | 2024 IS release | Current | Updated Apigee Edge base, improved S/4HANA adapters | Tighter BTP integration, better principal propagation |

[src1, src5, src8]

### Deprecation Policy

API gateway products generally follow cloud platform release cycles. Kong OSS follows semantic versioning with ~12-month support for major versions. AWS and Azure API Gateway services are fully managed with backward-compatible updates. SAP API Management follows BTP Integration Suite release cadence (quarterly). Apigee Edge (on-premises) is EOL — migrate to Apigee X. [src1, src5]

## When to Use / When Not to Use

| Use API Gateway When | Don't Use When | Use Instead |
|---|---|---|
| 6+ applications consume ERP APIs and you need unified auth/monitoring | Single iPaaS integration already handles auth, rate limiting, monitoring | iPaaS built-in API management |
| External partners or third parties need ERP data access | All consumers are internal services with direct network access | Direct API calls with retry logic |
| Multiple ERPs expose APIs and you need a unified consumer experience | Single ERP with well-documented native API | ERP native API directly |
| You need API versioning — proxy old paths to new ERP API versions | ERP API is stable with backward compatibility guarantees | ERP native versioning |
| You need response caching for ERP reference data (products, org hierarchy) | All data is transactional and must be real-time | Direct API calls |
| Azure APIM + Dynamics 365 (managed identity = zero-secret, natural fit) | You're adding Azure APIM just for a non-Azure ERP like Salesforce | Kong or Apigee (cloud-agnostic) |
| SAP BTP landscape needing API management for S/4HANA | Non-SAP landscape with no BTP investment | Third-party gateway |
| You need circuit breaker/retry at the edge before hitting ERP | iPaaS already has circuit breaker and retry policies | iPaaS error handling |

## Cross-System Comparison

### API Gateway vs iPaaS API Management Capabilities

| Capability | Standalone API Gateway (Kong/Apigee/AWS) | iPaaS API Management (MuleSoft/Boomi/SAP IS) | Notes |
|---|---|---|---|
| Rate limiting | Full (sliding window, quota, spike arrest) | Basic to full (varies by platform) | Standalone gateways are more configurable |
| Auth consolidation | Full (OAuth, JWT, API key, mTLS) | Full | Feature parity |
| Request transformation | Simple (headers, query, URL rewrite) | Full (complex object mapping, DataWeave) | iPaaS wins for complex transforms |
| Response caching | Full | Limited | Gateway is purpose-built for this |
| Circuit breaker | Full | Varies (MuleSoft yes, Boomi limited) | Gateway is more configurable |
| Developer portal | Full (Kong Dev Portal, Apigee portal) | Varies | Standalone gateways have better portals |
| API analytics | Full | Basic to full | Apigee excels here |
| Multi-ERP orchestration | No (single hop proxy) | Full (multi-step flows) | iPaaS core capability |
| Data validation | Basic (schema validation) | Full (field-level rules, cross-field) | iPaaS wins |
| Error recovery | Retry + circuit breaker | Full (DLQ, compensation, human task) | iPaaS wins for complex recovery |
| Deployment flexibility | Self-hosted, cloud, hybrid | Cloud-first (some support hybrid) | Kong wins for on-premise |
| Cost (mid-scale) | $0-$50K/yr (OSS to enterprise) | $50K-$200K+/yr | Gateway is cheaper if you don't need iPaaS |

[src4, src6]

## Important Caveats

- Gateway products evolve rapidly — Kong, Apigee, and Azure APIM release quarterly. Verify specific rate limit and transformation capabilities against current documentation before making architecture decisions. [src1]
- Cost comparisons are approximate and depend heavily on request volume, deployment model, and support tier. Request vendor quotes for your specific throughput requirements.
- SAP API Management is built on OEM Apigee Edge (not Apigee X) — Apigee Edge documentation may not match SAP's implementation exactly. Always reference SAP-specific documentation at help.sap.com. [src5]
- AWS API Gateway REST API has a hard 29-second timeout that cannot be increased. This eliminates it for synchronous bulk ERP operations. Use HTTP API type (30-minute timeout) or Application Load Balancer instead. [src8]
- This card covers the gateway pattern, not specific gateway product configuration. For production deployment, consult the gateway vendor's official hardening and HA documentation.
- The decision to add a gateway should be driven by consumer count and external access requirements, not by a checklist of gateway features. Many organizations add gateways for capabilities their iPaaS already provides.

## Related Units

- [ERP Rate Limits Comparison](/business/erp-integration/erp-rate-limits-comparison/2026)
- [iPaaS Platform Comparison](/business/erp-integration/ipaas-platform-comparison/2026)
- [ERP Authentication Comparison](/business/erp-integration/erp-authentication-comparison/2026)
- [Error Handling & Dead Letter Queues](/business/erp-integration/error-handling-dead-letter-queues/2026)
- [SAP BTP Integration vs Standalone iPaaS](/business/erp-integration/sap-btp-integration-vs-standalone-ipaas/2026)
- [MuleSoft Anypoint Capabilities](/business/erp-integration/mulesoft-anypoint-capabilities/2026)
- [Batch vs Real-time Integration](/business/erp-integration/batch-vs-realtime-integration/2026)
