> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# How Do OTPs Expire

> Explains how one time passwords expire by comparing time based authenticator codes and server stored SMS or email codes, including verification, TTLs, and security trade offs.

How do one-time passwords (OTPs) expire after a specific duration?

This article explains the two common OTP approaches and how expiration is enforced for each:

* Time-based OTPs generated by authenticator apps (TOTP).
* Short-lived, server-generated OTPs sent by email or SMS and stored server-side (commonly in Redis).

![The image shows two smartphone screens: one displaying an authenticator app with a six-digit OTP code and a circular timer, and the other showing a sign-in page with code entry boxes, a submit button, and a countdown saying the code expires. The header asks, "How do OTPs expire exactly after a specific duration?"](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Security/How-Do-OTPs-Expire/otp-expiration-authenticator-countdown-signin.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=09a79b0081c7c36cb4b704c8eefda83a)

## Overview — two OTP models

* TOTP: stateless (server derives valid codes from a shared secret + clock). Expiration is implicit because codes are tied to discrete time windows (e.g., 30s).
* SMS/Email OTP: stateful (server stores the generated code with an explicit TTL). Expiration is explicit: the server-side storage removes or ignores the code after its TTL.

Use the model that fits your security and UX needs: TOTP is more resilient to intercepts but needs initial secret setup; SMS/Email OTPs are simpler for users but more vulnerable to interception and SIM attacks.

## TOTP (Time-Based One-Time Passwords)

Authenticator apps (Google Authenticator, Authy, etc.) produce a short numeric code every fixed interval (commonly 30 seconds). The device can generate codes offline because both the server and the device share a secret key and rely on the current time.

How TOTP works (high level):

1. Both client (authenticator app) and server share a secret key (seed).
2. Time is split into fixed steps (usually 30-second windows).
3. Compute a time counter: `counter = floor(current_unix_time / step)`.
4. Use HMAC (commonly HMAC-SHA1) with the secret and counter.
5. Apply dynamic truncation and extract the last N digits (usually 6) to produce the numeric code.

Minimal conceptual Python-like sketch:

```python theme={null}
# pseudo-code (conceptual)
import hmac, hashlib, time

def totp(secret, digits=6, step=30, algo=hashlib.sha1):
    counter = int(time.time()) // step
    counter_bytes = counter.to_bytes(8, 'big')
    h = hmac.new(secret, counter_bytes, algo).digest()
    # dynamic truncation (standard RFC 6238 method)
    offset = h[-1] & 0x0F
    code = (int.from_bytes(h[offset:offset+4], 'big') & 0x7FFFFFFF) % (10**digits)
    return str(code).zfill(digits)
```

![An infographic explaining the Time-Based One-Time Password (TOTP) flow, showing a phone authenticator (example GitHub code 645 338) and a server sharing a secret key. It shows HMAC-SHA1 and 30-second time blocks used to generate the six-digit codes.](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Security/How-Do-OTPs-Expire/totp-authenticator-server-hmac-sha1-30s.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=6f7178825fe1988ae6b751e573e654d7)

Verification and expiration semantics

* The server computes the expected TOTP for the current time window and usually one or two adjacent windows to tolerate clock skew and small delays.
* A TOTP is valid only for its time window (e.g., the 30-second period). When the window ends, previously valid codes are no longer accepted (unless the server explicitly accepts the previous window).
* To prevent replay, servers should track the last accepted time counter per account and reject any code with a counter that was already used.

Common server behaviours

* Accept codes from the current and previous (and sometimes next) time windows to account for clock drift and network latency.
* Store the last accepted counter per user to prevent reuse of previously validated codes.
* If a code arrives right at a window boundary, accepting the previous window reduces false negatives.

![A diagram of a phone authenticator app showing a GitHub account and a 6‑digit code (923 970). To the right is a server-side flow illustrating HMAC‑SHA1 verification and time/block windows for TOTP codes.](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Security/How-Do-OTPs-Expire/phone-authenticator-github-totp-6digit-hmacsha1.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=d4ecfe6ebf0e498ec47f921d68296f8a)

Note: TOTP is specified in [RFC 6238](https://datatracker.ietf.org/doc/html/rfc6238) and is derived from HOTP (HMAC-based OTP, [RFC 4226](https://datatracker.ietf.org/doc/html/rfc4226)) by using a time-based counter rather than an incrementing counter.

Servers commonly allow a ±1 time-step tolerance to account for clock drift and network delay. They should still track and reject already-used counters to prevent replay.

## SMS / Email OTPs (server-generated, stored in Redis)

OTP codes delivered via SMS or email are generated and stored on the server with an explicit expiration time (TTL). These codes are stateful: once the server-side storage expires or is deleted, the code is no longer valid.

Typical flow:

1. Server generates a cryptographically secure random numeric code (e.g., 6 digits).
2. Server stores the code in a fast key-value store (Redis) with a TTL, for example 120 seconds (2 minutes).
3. Server sends the code to the user's phone or email.
4. When the user submits the code:
   * The server looks up the stored value.
   * If the key is missing (expired or never set), reject with "OTP expired."
   * If it matches, delete the key and accept (prevents reuse).
   * Otherwise, reject as invalid.

Example Redis commands:

```bash theme={null}
# Store a code with a 120-second expiry
SETEX "otp:user:12345" 120 814275

# Or using SET with EX and NX to avoid overwriting existing keys
SET "otp:user:12345" 814275 EX 120 NX
```

Verification pseudocode:

```python theme={null}
# pseudo-code for verification
stored = redis.get(f"otp:user:{user_id}")  # returns None if expired
if stored is None:
    # expired or never set
    reject("OTP expired")
elif stored == submitted_code:
    redis.delete(f"otp:user:{user_id}")  # prevent reuse
    accept("Authenticated")
else:
    reject("Invalid OTP")
```

Why expiration works here

* Redis enforces TTL: once the TTL elapses, reads return nothing (the key behaves as absent). Even if physical deletion is lazy internally, the logical result is that the code is unavailable after expiry.
* Deleting the key after successful validation prevents replay attacks.

## Comparison: TOTP vs SMS/Email OTP

| Characteristic | TOTP (authenticator apps) | SMS / Email (server-side) |
| - | -: | - |
| State on server | Stateless (server derives valid codes) | Stateful (server stores codes with TTL) |
| Offline capability | Yes (device generates codes offline) | No (server must generate and send) |
| Expiration mechanism | Implicit: tied to time windows (e.g., 30s) | Explicit: TTL in storage (e.g., Redis `EX`/`SETEX`) |
| Vulnerabilities | Clock skew, device compromise | Interception, SIM swap, email compromise |
| Replay protection | Track last-used time counter | Delete stored key on use |

## Security considerations and best practices

* Prefer TOTP or hardware-backed keys (U2F/WebAuthn) for high-security scenarios; SMS is susceptible to interception and SIM swap.
* Always enforce rate limits and brute-force protection (limit attempts per key or per user).
* Use cryptographically secure RNG for server-side codes.
* Delete OTPs on successful use to prevent replay attacks.
* Track last-used TOTP counter per account to avoid accepting reused codes.
* Monitor OTP endpoints for suspicious activity (failed attempts, repeated requests).

SMS-based OTPs can be intercepted or abused (SIM swap). Prefer authenticator apps or hardware keys for high-security requirements, and always implement rate-limiting and monitoring for OTP endpoints.

## Links and references

* RFC 6238 — TOTP: [https://datatracker.ietf.org/doc/html/rfc6238](https://datatracker.ietf.org/doc/html/rfc6238)
* RFC 4226 — HOTP: [https://datatracker.ietf.org/doc/html/rfc4226](https://datatracker.ietf.org/doc/html/rfc4226)
* Redis: [https://redis.io/](https://redis.io/)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/devops-interview-prep/module/6ea54e9c-4935-4be4-8955-674e08d91cc7/lesson/f72cf48b-e288-4e44-a135-ddca3bdea76d)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.