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

Limitando e aparando fluxos

Controle o crescimento da memória dos fluxos limitando o tamanho com MAXLEN, aparando por ID com MINID e usando o aparamento aproximado para obter desempenho.

Aula 4 de 413 etapas

Limitando e aparando fluxos é 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.

Streams Grow Forever

Unless told otherwise, a Redis Stream keeps every entry you append. For high-throughput producers this means unbounded memory growth. Capping and trimming let you keep streams to a manageable size.

Capping at Add Time

The cleanest approach is to cap during XADD using MAXLEN. Redis evicts the oldest entries to keep the length at or below the limit.

XADD events MAXLEN 1000 * action login user 42

Exact vs Approximate

Exact trimming can be costly. The ~ modifier requests approximate trimming, which is far cheaper because Redis only removes whole macro-nodes.

  • MAXLEN 1000 exact
  • MAXLEN ~ 1000 approximate, may keep slightly more
XADD events MAXLEN ~ 1000 * action click

Trimming After the Fact

You can trim an existing stream with XTRIM, using the same options as the XADD capping clause.

XTRIM events MAXLEN 500
XTRIM events MAXLEN ~ 500

Trimming by ID with MINID

Instead of length, you can trim by entry ID. MINID removes all entries older than a given ID, which maps naturally to time since IDs start with a millisecond timestamp.

XTRIM events MINID 1716900000000
XADD events MINID ~ 1716900000000 * a 1

Time-Window Retention

Because the first part of a stream ID is a Unix millisecond timestamp, MINID lets you keep only the last hour or day of events. Compute the cutoff timestamp in your app and pass it in.

# keep last 24h: cutoff = (now_ms - 86400000)
XTRIM events MINID 1716813600000

Limiting Eviction Work

The LIMIT option (with approximate trimming) caps how many entries a single trim removes, smoothing out latency spikes on very large streams.

XTRIM events MAXLEN ~ 1000 LIMIT 100

Checking Stream Length

Use XLEN to see the current entry count and XINFO STREAM for detailed metadata including first and last IDs.

XLEN events
XINFO STREAM events

Trimming and Consumer Groups

Trimming removes entries regardless of whether consumer groups have read them. If a slow consumer falls behind the trim point, those messages are lost for it. Size your cap to cover your slowest consumer's lag.

Choosing a Strategy

Use MAXLEN when you care about count and bounded memory. Use MINID when you care about a time window. Prefer the ~ approximate form in production for performance unless exact bounds are required.

Memory in Practice

Capping at add time is usually best: it keeps memory steady without a separate cleanup job. Reserve XTRIM for ad-hoc cleanups or when retention rules change.

Quick Check

Test your understanding of stream trimming.

Recap

You learned to control stream growth with MAXLEN capping, MINID time-window trimming, the cheaper ~ approximate mode, the LIMIT option to bound eviction work, and the caveat that trimming can drop messages slow consumers have not yet read.

Grátis para começar

Aprenda Redis Caching & Messaging (Pub/Sub, Streams) com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
12
Aulas
48

Perguntas Frequentes

A aula “Limitando e aparando fluxos” é grátis?

Sim — o texto completo de “Limitando e aparando fluxos” é 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 “Limitando e aparando fluxos”?

Controle o crescimento da memória dos fluxos limitando o tamanho com MAXLEN, aparando por ID com MINID e usando o aparamento aproximado para obter desempenho. 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 “Limitando e aparando fluxos”?

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. O que são os Redis Streams?
  2. Estruturas de dados e comandos de fluxo
  3. Persistência de mensagens em fluxos
  4. Limitando e aparando fluxos
← Voltar para Redis Caching & Messaging (Pub/Sub, Streams)