Databases2 minutes to read

How do I make a bot’s Redis cache expire automatically?

Set a Redis value and its lifetime together, interpret TTL results, and distinguish stale cache entries from records your application must keep.

Set an expiration when you write the value

Write a cache entry with Redis SET and an expiration such as EX 300 for five minutes. This sets the value and lifetime in one command, so a process that stops immediately after the write cannot leave that new entry without its timer. Use a cache for answers you can fetch or compute again.

Suppose a bot displays the next event from a club calendar. Caching that answer for five minutes avoids repeated calendar calls when several people ask at once. Keep RSVP records or paid bookings in storage with a retention policy suited to those records. Expiring the cached event title should simply cause the next request to read the calendar again.

Try a short-lived test key

Open a TLS session to your own database using the Bothosting Redis connection guide. The following commands run inside that connected Redis client. Use a fresh test key that your live bot does not read.

Write a 30-second sample and check the remaining time
SET demo:calendar:next "Friday meetup" EX 30
GET demo:calendar:next
TTL demo:calendar:next

The first read should return the event title. The next command reports the remaining seconds. After 30 seconds, read it again. A missing value and TTL of -2 mean the key is absent. A result of -1 means the key exists without an expiration. See the Redis TTL reference.

Check the refresh path too

Send the same bot command after the test cache has expired. Watch for one successful calendar fetch and a newly populated key with a positive lifetime. If your refresh code writes the key again using plain SET, the previous expiration is removed. Include the intended lifetime on replacement writes. On Bothosting’s Redis profile, memory pressure can cause writes to fail under its no-eviction policy, so handle a failed cache write separately from a successful calendar response.