0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · Aula

Expiração de chaves e TTL no Redis

Aprenda como o Redis permite associar valores de duração às chaves para que expirem automaticamente, quais comandos controlam TTL e como o Redis decide quando remover chaves expiradas.

Expiração de chaves e TTL no Redis é uma aula grátis de Redis Caching & Messaging (Pub/Sub, Streams) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Redis Caching & Messaging (Pub/Sub, Streams), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Why Keys Need to Expire

Redis often holds temporary data — sessions, one-time codes, cached responses. Expiration lets a key delete itself after a set time so memory stays lean.

Setting a TTL with EXPIRE

EXPIRE attaches a time-to-live in seconds to an existing key. Once the clock runs out, the key vanishes. See the example below.

SET session:42 "active"
EXPIRE session:42 3600

Set and Expire in One Step

Set value and TTL together with SET ... EX — safer than two separate commands, since there's no window where the key has no expiry.

SET otp:99 "123456" EX 300

Checking Remaining Time

TTL returns the seconds left on a key. It returns -1 if the key has no expiry, and -2 if the key doesn't exist at all.

TTL session:42

Millisecond Precision

For finer control, PEXPIRE and PTTL work in milliseconds instead of seconds. The code below sets and reads a millisecond TTL.

PEXPIRE otp:99 1500
PTTL otp:99

Expiring at a Specific Time

EXPIREAT takes a Unix timestamp, so a key can die at an exact wall-clock moment — like precisely at midnight.

EXPIREAT daily:report 1893456000

Removing an Expiry

PERSIST strips a key's TTL, making it permanent again — handy when temporary data gets promoted to durable.

PERSIST session:42
TTL session:42

How Redis Deletes Expired Keys

Redis removes expired keys two ways: lazy deletion checks on access, and active deletion samples keys in a background task and purges expired ones.

Writes Can Clear TTL

Watch out: a plain SET (no EX) overwrites a value and clears its existing TTL. Modifying commands like APPEND or INCR keep the TTL intact.

Common Use Cases

TTL powers real patterns: auto-expiring sessions, rate-limit counters, one-time passwords and verification tokens, and caches that refresh after N seconds.

Keyspace Notifications on Expiry

Redis can publish an event when a key expires via keyspace notifications, so your app can react. Enable expired-key events, then subscribe. See below.

CONFIG SET notify-keyspace-events Ex
SUBSCRIBE __keyevent@0__:expired

Quick Check

Test your expiration knowledge.

Recap

Recap: EXPIRE and SET ... EX set a TTL, TTL reads it (-1 none, -2 missing), PEXPIRE/EXPIREAT give finer control, PERSIST removes it, plain overwrites clear it.

Perguntas Frequentes

A aula “Expiração de chaves e TTL no Redis” é grátis?

Sim — o texto completo de “Expiração de chaves e TTL no Redis” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Redis Caching & Messaging (Pub/Sub, Streams), atualize para CoddyKit PRO. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.

O que vou aprender em “Expiração de chaves e TTL no Redis”?

Aprenda como o Redis permite associar valores de duração às chaves para que expirem automaticamente, quais comandos controlam TTL e como o Redis decide quando remover chaves expiradas. Você pratica Redis Caching & Messaging (Pub/Sub, Streams) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Redis Caching & Messaging (Pub/Sub, Streams)?

Nenhuma experiência prévia é necessária. Redis Caching & Messaging (Pub/Sub, Streams) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Expiração de chaves e TTL no Redis”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Redis Caching & Messaging (Pub/Sub, Streams)?

Sim. Cada aula de Redis Caching & Messaging (Pub/Sub, Streams) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Introdução ao Redis
  2. Noções básicas da CLI do Redis
  3. Estruturas de dados fundamentais do Redis
  4. Expiração de chaves e TTL no Redis
← Voltar para Redis Caching & Messaging (Pub/Sub, Streams)