# Key Expiry (TTL) — Redis Fundamentals: Caching, Data Structures and Persistence

Source: https://www.skillbyai.com/en/redis/redis-key-expiry

> Expire keys automatically with EXPIRE, TTL and SET EX so Redis works as a self-cleaning cache.

## EXPIRE & TTL

`EXPIRE` sets a countdown in seconds after which the key is deleted; `TTL` checks how much time is left.

```bash
SET otp:9876 "4521"
EXPIRE otp:9876 60
TTL otp:9876
```

Output:

```
OK
(integer) 1
(integer) 58
```

## Expiry in one line

`SET key value EX seconds` sets the value and TTL together — no separate `EXPIRE` call needed.

```bash
SET session:abc "user42" EX 1800
SETEX cache:homepage 300 "<html>...</html>"
```

## Why expiry matters

TTLs let Redis act as a self-cleaning cache — stale data times out on its own instead of piling up in memory forever.
