DEV Community

Jbee - codehooks.io
Jbee - codehooks.io

Posted on

Tutorial part-5: key-value store - TTL options

Welcome to this part-5 of the key-value database tutorial for codehooks.io serverless Node.js backend. In this part we'll cover the time-to-live (TTL) feature in the Codehooks key-value database.

This article is also available at the official codehooks.io website

The TTL database feature allows you to associate an expiration time with each key-value pair. Once the TTL for a particular key expires, the key-value pair is automatically removed from the database.

Some common use cases for the TTL features are listed below:

  1. Cache Expiration: Implement TTL in your cache to automatically remove stale data and ensure fresh content is served to users, improving website performance.
  2. Session Management: Set TTL for user sessions in your web application to automatically remove expired sessions, enhancing security and freeing up server resources.
  3. Temporary Data Storage: Use TTL to store temporary data, such as shopping cart information or form submissions, and automatically remove it after a certain period to avoid cluttering the database.
  4. Logging: Apply TTL to store logs or activity data for a limited duration, ensuring the database remains focused on recent and relevant information.
  5. Rate Limiting: Utilize TTL to enforce rate limits for API calls or user interactions, automatically resetting counters or restrictions after a specific time interval.

Example code using the TTL feature

The example code below shows how to create a REST API to POST a temporary state value to a particular key. The state will be kept for 24 hours by the TTL feature.

// keep state for 24 hours
app.post('/state/:id', async (req, res) => {
  const ONE_DAY = 86400000; // One day in millis
  // get id from request parameter
  const {id} = req.params;
  // state is the raw JSON body
  const state = req.body;
  // connect to data store
  const conn = await Datastore.open();
  const opt = {
      "ttl": ONE_DAY
  };
  // set state with TTL option
  const result = await conn.set(`state-${id}`, JSON.stringify(state), opt);
  res.json(result);
})
Enter fullscreen mode Exit fullscreen mode

Furthermore, the next code example shows how we can create a REST API to retrieve the state value within the 24 hour TTL time frame. If the state exists is is returned, otherwise a 404 status code is returned.

// get state or 404 if TTL expired
app.get('/state/:id', async (req, res) => {
  // get id from request parameter
  const {id} = req.params;
  const conn = await Datastore.open();
  // get state from database or NULL if key is deleted
  const result = await conn.get(`state-${id}`);
  if (result === null) {
    res.status(404).send('No state')
  } else {
    res.set('content-type', 'application/json');
    res.send(result);
  }
})
Enter fullscreen mode Exit fullscreen mode

These simple examples shows how easy it is to implement various use cases with the TTL feature.

Overall, the TTL feature in the key-value database provides flexibility and automation for managing data expiration, allowing you to optimize performance, storage, and overall system efficiency.

In our next upcoming tutorial Part-6: Multiple key spaces, we'll cover the option to split your key-value database into multiple logical data spaces.

Top comments (0)