Lesson 1
Managing User Data with Expiration
Managing User Data with Expiration

Welcome to the first step in building our Redis-based backend system. In this unit, we will focus on how to manage user data with expiration using Redis in PHP. This is a fundamental part of our project that will set the stage for more advanced features in later units.

What You'll Build

In this unit, we will implement two primary operations for managing user data using PHP:

  1. Adding user data with an expiration time: This ensures that user data is stored only for a specified duration before being automatically deleted.
  2. Retrieving user data: This allows us to fetch the stored user data.

Here is a PHP code example to help illustrate these operations:

php
1<?php 2 3require 'vendor/autoload.php'; 4 5use Predis\Client; 6 7$client = new Client(); 8 9$data = [ 10 'email' => 'user1@example.com', 11]; 12 13// Add user data with expiration 14$client->set('user:1', $data['email']); 15$client->expire('user:1', 24 * 60 * 60); // 24 hours in seconds 16 17// Retrieve user data 18$val = $client->get('user:1'); 19if ($val) { 20 echo "Retrieved user data: " . $val . "\n"; 21} else { 22 echo "Error retrieving user data.\n"; 23}

In this example, set is used to store user data, and expire is used to set the expiration time, which is specified as 24 * 60 * 60 to represent a duration of one day in seconds. The get method is used to retrieve the stored data.

The expire method is called separately from set because, by default, set does not automatically associate an expiration time with the key. If you want to set a key with an expiration in one step, you can use setex, which both stores the value and sets an expiration time:

php
1$client->setex('user:1', 24 * 60 * 60, $data['email']);

This eliminates the need for a separate expire call and ensures atomicity.

Redis provides a built-in mechanism to automatically delete keys when their expiration time is reached. This is particularly useful for managing temporary data, such as session tokens, one-time authentication codes, or cache entries, without the need for manual cleanup. When a key expires, Redis removes it from memory, making it an efficient solution for handling time-sensitive user data.

There are two strategies for key expiration:

  • Passive deletion: If a client attempts to access an expired key, Redis will check its expiration time and remove it before returning a response.
  • Active deletion: Redis periodically scans a subset of keys with expiration times and removes those that are expired. However, this does not guarantee immediate removal of all expired keys.

This foundational knowledge will prepare you for more complex tasks in upcoming lessons. Let's move on to practice implementing this logic to reinforce your understanding.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.