Akamai CDN: The Definitive Developer’s Reference

Introduction to Akamai CDN

Akamai is one of the world’s largest Content Delivery Network (CDN) providers, operating over 325,000 servers in more than 135 countries. It delivers between 15-30% of all web traffic and helps businesses accelerate content delivery, enhance website performance, improve security, and scale globally. As a pioneer in the CDN industry since 1998, Akamai provides a distributed platform that reduces latency by placing content closer to end users, shields origin servers from direct traffic, and offers numerous performance and security optimizations.

Core Concepts & Architecture

ConceptDescription
Edge ServersDistributed servers that cache and deliver content close to end users
Origin ServerYour web server where original content is hosted
Edge NetworkAkamai’s global network of distributed servers
PoPs (Points of Presence)Physical locations containing edge servers
CachingStoring copies of content on edge servers to reduce latency
Content PurgingProcess of removing content from the cache
Edge ComputeRunning code at the edge for performance and customization

Akamai Platform Components

  • Intelligent Platform: Core infrastructure for content delivery and acceleration
  • Control Center: Web portal for managing Akamai services
  • Luna Portal: Management interface for configuration and reporting
  • Property Manager: Tool for creating and managing property configurations
  • EdgeWorkers: JavaScript-based edge computing platform
  • Image Manager: Automated image optimization service
  • Ion: Web performance solution suite
  • Kona Security Solutions: Web security products including WAF

Akamai Configuration Basics

Property Configuration Structure

Property
  └── Property Hostname(s)
      └── Property Configuration
          └── Default Rule
              ├── Behaviors
              └── Child Rules
                  └── Behaviors & Criteria

Common Property Manager Behaviors

BehaviorPurpose
Origin ServerDefine the origin hostname, path, and connection settings
CachingConfigure cache TTL and validation behavior
Content CompressionEnable/configure GZIP/Brotli compression
Last Mile AccelerationOptimize delivery over the last network hop
Prefresh CacheProactively refresh cached content before expiration
Site FailoverConfigure failover destinations if origin is unavailable
Adaptive AccelerationAutomatically optimize based on real user metrics
Advanced Cache ControlFine-tune caching behavior with detailed settings

Common Property Manager Match Criteria

CriteriaPurpose
PathMatch based on the request path
Filename ExtensionMatch specific file types
Query String ParameterMatch based on query parameters
CookieMatch based on cookie values
Client IPMatch specific IP addresses/ranges
Request MethodMatch specific HTTP methods (GET, POST, etc.)
User AgentMatch based on browser/device information
Response CodeMatch based on HTTP response code

Caching Configuration

Cache TTL Settings

// Sample Property Manager caching settings
"behaviors": [
  {
    "name": "caching",
    "options": {
      "behavior": "MAX_AGE",
      "mustRevalidate": false,
      "ttl": "1d"
    }
  }
]

Common Cache Time Values

Content TypeRecommended TTL
Static Assets (CSS/JS)7-30 days
Images30 days
HTML0 minutes (no caching) to 1 hour
API ResponsesVaries by use case (0 min to 1 day)
Error Pages5-10 minutes

Cache-Control Directives

DirectiveEffect
max-ageSpecifies TTL in seconds
s-maxageSpecific to shared caches like CDNs
no-cacheMust revalidate before serving cached content
no-storeDon’t cache at all
privateOnly cacheable in browser, not CDN
publicCacheable by browsers and CDNs
must-revalidateMust revalidate after expiration

Content Purging Methods

  1. Fast Purge API:
curl -X POST "https://api.ccu.akamai.com/ccu/v3/invalidate/url" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"objects": ["https://www.example.com/path/to/asset.jpg"]}'
  1. Purge by Content Provider Code (CPCODE):
curl -X POST "https://api.ccu.akamai.com/ccu/v3/invalidate/cpcode" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"objects": [12345]}'
  1. Via Luna Control Center:
    • Navigate to Purge → Create a New Purge
    • Select purge type (URL, CPCODE, Cache Tag)
    • Enter objects to purge
    • Submit request

Performance Optimization Techniques

Optimizing Origin Connectivity

  • Origin Connection Settings: Configure persistent connections, request timeouts
  • Forward Host Headers: Control the Host header sent to origin
  • Allow/Deny Origin IPs: Restrict origin access to Akamai IPs only

Image & Resource Optimization

  • Image Manager: Automatic device-specific image optimization
  • Adaptive Image Compression: Adjusts compression based on network conditions
  • Image & Midgress Cache Optimization: Fine-tune image delivery
  • Prefetching: Preload resources before they’re requested

Front-End Optimization

  • Resource Minification: Minimize CSS, JS, and HTML
  • Resource Consolidation: Combine multiple resources
  • Adaptive Acceleration: Automatically optimize based on network conditions
  • Script Management: Control script loading and execution
  • Lazy Loading: Defer loading of non-critical assets

Mobile Optimization

  • Responsive Image Delivery: Serve device-appropriate images
  • Mobile Detection: Detect and adapt to mobile devices
  • Transcoding: Convert content formats for mobile compatibility
  • Mobile Redirect: Redirect mobile users to mobile-specific experiences

Security Features

Web Application Firewall (WAF) Configuration

  • Rule Sets: Predefined security rules (OWASP Top 10, etc.)
  • Custom Rules: Create custom security rules
  • Rate Controls: Limit request rates to prevent abuse
  • IP/Geo Blocking: Block specific regions or IP addresses
  • Bot Manager: Identify and control bot traffic
  • API Gateway: Secure and manage API traffic

SSL/TLS Configuration

  • Shared Certificates: Use Akamai-managed shared certificates
  • Custom Certificates: Upload and manage your own certificates
  • SNI: Configure Server Name Indication for multiple hostnames
  • TLS Versions: Control supported TLS versions (1.2, 1.3)
  • Cipher Suites: Configure supported encryption methods

DDoS Protection

  • Site Shield: Hide origin from direct access
  • Prolexic: Protection against large-scale DDoS attacks
  • Rate Controls: Limit request rates
  • Security Monitors: Real-time attack monitoring

EdgeWorkers (Edge Computing)

EdgeWorkers Lifecycle Events

EventPurpose
onClientRequestExecutes when request is received from client
onOriginRequestExecutes before request is sent to origin
onOriginResponseExecutes after response is received from origin
onClientResponseExecutes before response is sent to client

Sample EdgeWorker Code

// main.js
import { logger } from 'log';
import { createResponse } from 'create-response';

export function onClientRequest(request) {
  // Add a custom request header
  request.setHeader('X-Custom-Header', 'EdgeWorker-Value');
  
  // Log the client IP
  logger.log('Client IP: %s', request.userLocation.clientIp);
}

export function onOriginResponse(request, response) {
  // Modify the response headers
  response.setHeader('X-Powered-By', 'Akamai EdgeWorkers');
  
  // If response is JSON, parse and possibly modify it
  if (response.getHeader('Content-Type') === 'application/json') {
    return response.text().then(responseText => {
      const jsonData = JSON.parse(responseText);
      
      // Modify the JSON
      jsonData.processedBy = 'EdgeWorkers';
      
      // Return modified response
      return createResponse(
        200,
        {'Content-Type': ['application/json']},
        JSON.stringify(jsonData)
      );
    });
  }
}

EdgeWorkers Deployment

  1. Create EdgeWorker ID in Control Center
  2. Bundle code (main.js + bundle.json)
  3. Upload bundle using API or Control Center
  4. Activate version in staging/production
  5. Add EdgeWorkers behavior to Property

API Gateway

API Gateway Key Features

  • API Security: Authentication, authorization, and input validation
  • Rate Limiting: Control request rates per API key/client
  • Quota Management: Limit usage over time periods
  • Analytics: Monitor API usage and performance
  • Versioning: Manage multiple API versions
  • Caching: Cache API responses at the edge

API Authentication Methods

MethodUse Case
API KeysSimple authentication with keys in header or query parameter
OAuth 2.0Token-based authorization for more secure access
JWTJSON Web Tokens for stateless authentication
IP/Geo RestrictionsRestrict access based on caller location

Common Troubleshooting Techniques

Debugging Tools

  • Akamai Debug Headers: Add Pragma: akamai-x-check-cacheable and similar debug headers
  • Akamai Diagnostic Tools: Control Center troubleshooting utilities
  • Log Delivery Service (LDS): Configure and analyze logs
  • Real User Monitoring (RUM): Analyze real user performance data
  • Akamai CLI: Command-line tools for troubleshooting

Key Debug Headers

HeaderPurpose
X-CacheShows cache hit/miss status
X-Cache-KeyShows the cache key used
X-Cache-RemoteIndicates if served from parent cache
X-Check-CacheableShows if content is cacheable
X-Akamai-Request-IDUnique identifier for request tracking

Testing Cache Status

# Test cache status with curl
curl -I -H "Pragma: akamai-x-check-cacheable" https://www.example.com/path/to/asset

Common Error Responses

ErrorPossible Causes
503 Service UnavailableOrigin server unavailable or timeout
504 Gateway TimeoutOrigin not responding within timeout period
502 Bad GatewayOrigin returned invalid response
403 ForbiddenWAF blocks, IP restrictions, or authentication failures
404 Not FoundResource not found on origin or edge

Real-World Optimization Scenarios

High-Traffic Media Site

  1. Aggressive caching of static assets (30+ days)
  2. Image Manager for automatic optimization
  3. Prefetching for anticipated user journeys
  4. Tiered Distribution to handle traffic surges
  5. Cache Tag-based purging for content updates

E-commerce Site

  1. Selective caching (static content vs. dynamic)
  2. Edge Side Includes (ESI) for personalized components
  3. A/B Testing at the edge
  4. API Acceleration for product and inventory calls
  5. Bot management to protect against scraping

Mobile App Backend

  1. API Gateway for security and rate limiting
  2. JSON optimization for bandwidth reduction
  3. Push APIs for notification delivery
  4. Mobile performance optimizations
  5. Geolocation-based content customization

Configuration Examples

Basic Origin Configuration

{
  "rules": {
    "behaviors": [
      {
        "name": "origin",
        "options": {
          "originType": "CUSTOMER",
          "hostname": "origin.example.com",
          "forwardHostHeader": "ORIGIN_HOSTNAME",
          "cacheKeyHostname": "ORIGIN_HOSTNAME",
          "compress": true,
          "enableTrueClientIp": true
        }
      }
    ]
  }
}

Caching Strategy for Different Content Types

{
  "rules": {
    "children": [
      {
        "name": "Static Assets",
        "criteria": [
          {
            "name": "fileExtension",
            "options": {
              "matchOperator": "IS_ONE_OF",
              "values": ["css", "js", "jpg", "png", "gif", "svg"]
            }
          }
        ],
        "behaviors": [
          {
            "name": "caching",
            "options": {
              "behavior": "MAX_AGE",
              "ttl": "30d"
            }
          }
        ]
      },
      {
        "name": "HTML Content",
        "criteria": [
          {
            "name": "fileExtension",
            "options": {
              "matchOperator": "IS_ONE_OF",
              "values": ["html", "htm"]
            }
          }
        ],
        "behaviors": [
          {
            "name": "caching",
            "options": {
              "behavior": "MAX_AGE",
              "ttl": "1h"
            }
          }
        ]
      },
      {
        "name": "API Responses",
        "criteria": [
          {
            "name": "path",
            "options": {
              "matchOperator": "MATCHES_ONE_OF",
              "values": ["/api/*"]
            }
          }
        ],
        "behaviors": [
          {
            "name": "caching",
            "options": {
              "behavior": "NO_STORE"
            }
          }
        ]
      }
    ]
  }
}

Best Practices & Tips

Performance Best Practices

  • Cache as much as possible for as long as possible
  • Use Cache Tags for efficient content invalidation
  • Enable Brotli compression for text-based content
  • Implement Adaptive Image Compression for varying networks
  • Use prefetch hints for common user journeys
  • Enable HTTP/2 and HTTP/3 where supported
  • Implement Resource Timing API for performance monitoring

Security Best Practices

  • Apply the Principle of Least Privilege for origin access
  • Enable Site Shield to hide your origin
  • Implement Content Security Policy (CSP) headers
  • Use Strict Transport Security (HSTS) headers
  • Configure Client Reputation scoring
  • Enable Bot Manager for bot control
  • Regularly review Security Monitor reports

Operational Tips

  • Create a purge strategy before implementation
  • Use Staging environment for testing before production
  • Implement gradual rollouts of major changes
  • Set up Real User Monitoring for performance metrics
  • Configure Log Delivery Service for troubleshooting
  • Use Property Variables for environment-specific settings
  • Leverage Property Manager templates for consistency

Resources for Further Learning

Documentation & Learning

Tools & Utilities

Training & Certification

Scroll to Top