API Gateway #

In modern cloud computing architecture applying microservices and serverless patterns, APIs act as the main entrance connecting the outside world (clients like web apps, mobile apps, or IoT devices) with our backend services. Managing APIs independently on traditional servers requires major effort: we must handle reverse proxy configuration (like Nginx), manage SSL certificates, apply rate limiting rules, and handle user authentication manually.

Within the AWS ecosystem, AWS API Gateway comes in as a fully managed, serverless API management platform. This service frees us from all that infrastructure operational burden. API Gateway can manage, secure, scale, and monitor thousands of API calls simultaneously, automatically. This article will deeply dissect the API types in API Gateway, security mechanisms, async integration, and real implementation code examples.


API Types in AWS API Gateway #

AWS API Gateway provides three main API types optimized for different performance, feature, and budget needs.

1. HTTP API (Primary Recommendation) #

HTTP API is designed specifically for building high-performance, ultra-low-latency, low-cost APIs. It’s a minimalist version optimized for direct integration with Lambda functions or Application Load Balancers (ALBs).

  • Strengths: Costs up to 70% cheaper than traditional REST API type, much lower internal processing latency, and native OIDC/OAuth2 integration support.
  • Limitations: Doesn’t support complex features like built-in API Keys, Usage Plans, built-in caching, or advanced request/response transformation.
  • Best Use Cases: Standard RESTful APIs for modern web/mobile backends, async microservice integration.

2. REST API #

REST API is the classic version, rich in request/response manipulation features and enterprise-level API consumer management.

  • Strengths: Provides complete management features like API Keys creation, quota limits (Usage Plans), CDN-level response caching, WAF (Web Application Firewall) protection, and built-in XML-to-JSON transformation using Apache Velocity Templates.
  • Limitations: Slightly higher processing latency and more expensive data transfer and invocation costs.
  • Best Use Cases: Paid public APIs (SaaS) needing quota-based monetization, legacy APIs needing gateway-level data transformation.

3. WebSocket API #

WebSocket API is used for building stateful, real-time, bidirectional communication applications.

  • Strengths: API Gateway manages persistent TCP connections with clients at the gateway level, serverlessly. Backend Lambda functions are only invoked when a message is sent or a connection is closed, saving costs.
  • Best Use Cases: Chat applications, real-time instant notifications, live monitoring dashboards, and online games.

API Gateway Routing and Security Flow #

API Gateway acts as the first security gateway before client requests touch our backend code.

flowchart TD
    Client["Client (Web/Mobile)"] -->|1. Request with Bearer Token| APIGW["Amazon API Gateway"]
    
    subgraph Auth["Security Process"]
        APIGW -->|2. Validate Token| AuthLambda["Custom Lambda Authorizer"]
        AuthLambda -->|3. Return IAM Policy<br/>Allow/Deny| APIGW
    end
    
    APIGW -->|4. If Allow, Route to| Integration{"Integration Type"}
    
    subgraph Backend["Backend Execution"]
        Integration -->|Lambda Proxy| Lambda["Lambda Function"]
        Integration -->|Direct AWS Integration| SQS["Amazon SQS (Queue)"]
        Integration -->|HTTP Proxy| HTTP["External Server"]
    end
    
    Lambda -->|5. Return Response| APIGW
    SQS -->|5. Return Accepted| APIGW
    HTTP -->|5. Return Response| APIGW
    
    APIGW -->|6. Send Response to| Client

Authentication and Authorization Mechanisms: #

  1. IAM Authorization: Uses AWS key signatures (Signature Version 4) to secure communication between internal AWS services or access from client applications integrated with IAM credentials.
  2. Cognito User Pools Authorizer: Native integration with Amazon Cognito to validate JWT (JSON Web Tokens) from users who successfully logged in via OAuth2.
  3. Custom Lambda Authorizer: A custom Lambda function we write to validate our own security tokens (e.g., custom JWTs or third-party session tokens) and return an IAM Policy document determining whether the client is allowed (Allow) or denied (Deny) access to that resource path.

Rate Limiting Mechanism (Throttling) #

To protect our backend from denial-of-service (DDoS) attacks or unexpected traffic surges (thundering herd), API Gateway applies request rate limits using the Token Bucket algorithm.

  • Rate (RPS): The average number of requests per second allowed to flow steadily to the backend.
  • Burst: The maximum instant bucket capacity for handling very fast request surges in milliseconds.

If a client sends requests exceeding the Rate + Burst limit, API Gateway immediately cuts the request at the gateway level and returns the HTTP 429 Too Many Requests error status without forwarding it to the backend Lambda, securing our compute resources.


Direct AWS Proxy Integration #

One of the secrets of high-performance, cost-efficient architecture on AWS is Direct AWS Service Integration.

Many beginner teams deploy the flow: API Gateway -> Lambda -> SQS. The only purpose is to put request data into a queue. This pattern wastes Lambda invocation costs and adds cold start latency.

API Gateway supports direct integration to AWS services without a Lambda intermediary. We can configure a /submit-order route on API Gateway to write HTTP payloads directly into an Amazon SQS queue asynchronously using an abstracted payload format at the gateway. This cuts Lambda compute costs by up to 100% for initial data delivery flows.


Implementation Example: Custom Lambda Authorizer #

Here’s an example of Node.js code for a Lambda Authorizer function that validates the Authorization header token and returns an Allow/Deny IAM policy document.

// CORRECT: Generating a structured IAM Policy securely
export const handler = async (event) => {
    // Get the token from the Authorization header
    const token = event.headers?.authorization || event.headers?.Authorization;

    if (!token) {
        console.log("Token not found in request headers.");
        throw new Error("Unauthorized"); // Returns HTTP 401 Unauthorized
    }

    try {
        // Run token validation logic (Simulated JWT validation)
        const userPayload = validateToken(token);
        
        // Create the IAM Policy Document
        const principalId = userPayload.userId;
        const effect = userPayload.role === "admin" ? "Allow" : "Deny";
        const methodArn = event.routeArn; // ARN of the route being accessed

        console.log(`User ${principalId} verified with result: ${effect}`);
        
        return generatePolicy(principalId, effect, methodArn);

    } catch (err) {
        console.error("Token validation failed", err);
        throw new Error("Unauthorized");
    }
};

// Helper function to validate the JWT token (Simulation)
function validateToken(token) {
    if (token === "Bearer secret-admin-token") {
        return { userId: "user-123", role: "admin" };
    } else {
        throw new Error("Invalid token");
    }
}

// Helper function to build the IAM Policy document
function generatePolicy(principalId, effect, resource) {
    const authResponse = {
        principalId: principalId
    };

    if (effect && resource) {
        const policyDocument = {
            Version: '2012-10-17',
            Statement: [
                {
                    Action: 'execute-api:Invoke',
                    Effect: effect,
                    Resource: resource
                }
            ]
        };
        authResponse.policyDocument = policyDocument;
    }

    // Inject additional context for the following backend Lambda to read
    authResponse.context = {
        userId: principalId,
        scope: "write:orders"
    };

    return authResponse;
}

Summary #

  • AWS API Gateway is a serverless API management platform acting as the main, secure, scalable, fully managed entrance for our applications.
  • HTTP API is the primary choice for modern RESTful APIs because it offers faster internal processing latency and 70% lower costs.
  • REST API provides complete enterprise features like built-in API Keys, quota limits (Usage Plans), gateway-level caching, and WAF integration.
  • Token Bucket-based throttling must be configured at the gateway level to protect backend systems from request spam attacks (HTTP 429).
  • Use Direct AWS Service Integration (like writing directly to SQS from API Gateway) to eliminate the need for an intermediary Lambda and cut costs.
← Previous: Aurora   Next: Terraform →

About | Author | Content Scope | Editorial Policy | Privacy Policy | Disclaimer | Contact