Don’t Hardcode Cache TTL β€” Use What the API Tells You

Table of Contents

πŸ“– 1 minute read

Working with an API that returns authentication tokens? Don’t hardcode the cache TTL. The API already tells you when the token expires β€” use it.

The Common Mistake

// ❌ Hardcoded β€” what if the API changes expiry?
Cache::put('api_token', $token, 3600);

Hardcoding means your cache could expire before the token does (wasting API calls) or after it does (causing auth failures).

The Fix

// βœ… Dynamic β€” uses what the API tells you
$response = Http::post('https://api.example.com/auth', [
    'client_id' => config('services.api.client_id'),
    'client_secret' => config('services.api.client_secret'),
]);

$data = $response->json();
$token = $data['access_token'];
$expiresIn = $data['expires_in']; // seconds

// Cache with a small buffer (expire 60s early)
Cache::put('api_token', $token, $expiresIn - 60);

The expires_in field is there for a reason. Subtract a small buffer (30-60 seconds) to avoid edge cases where your cache and the token expire at the same instant.

Takeaway

Let the API dictate your cache duration. It’s one less magic number in your codebase, and it automatically adapts if the provider changes their token lifetime.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *