Issue with Redis cache time-to-live not adhering to set expiration

I have encountered an issue while using IoRedis and DragonflyDB to implement rate limiting in my web application. Despite setting a TTL of 5 seconds for the keys in the Redis DB, sometimes they do not expire as expected. I am struggling to understand why this is happening and unable to replicate the issue. Can anyone offer any insights or suggestions?

type RateLimitData = { [key: string]: number };

const prefix = 'rateLimit';
const ttl = 5;

const create = async (userId: string, path: string): Promise<void> => {
  const data = { [path]: 1 };
  await redis.call(
    'JSON.SET',
    `${prefix}:${userId}`,
    '$',
    JSON.stringify(data)
  );
  await redis.expire(`${prefix}:${userId}`, ttl);
};

const update = async (userId: string, path: string): Promise<void> => {
  const previousCache = await get(userId);

  if (previousCache) {
    const aggregate = previousCache[path] ? previousCache[path] + 1 : 1;
    const updatedCache = { ...previousCache, [path]: aggregate };
    await redis.call(
      'JSON.SET',
      `${prefix}:${userId}`,
      '$',
      JSON.stringify(updatedCache)
    );
  } else {
    await create(userId, path);
  }
};

const get = async (userId: string): Promise<RateLimitData | null> => {
  const data = await redis.call('JSON.GET', `${prefix}:${userId}`);
  if (!data) return null;

  return JSON.parse(data as string) as RateLimitData;
};

export const rateLimit = { create, update, get };

Dragonfly version:

docker.dragonflydb.io/dragonflydb/dragonfly:v1.2.1

"ioredis": "^5.3.2",

Answer №1

When you perform an update that replaces the value for a key, the timeout is removed. It seems likely that the keys which never expire have been updated.

Based on information from the "expire" command in Dragonfly documentation (similar to Redis):

The timeout will only be cleared by commands that delete or overwrite the contents of the key, such as DEL, SET, GETSET, and other *STORE commands.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered: The property 'localStorage' is not found on the 'Global' type

Calling all Typescript enthusiasts! I need help with this code snippet: import * as appSettings from 'application-settings'; try { // shim the 'localStorage' API with application settings module global.localStorage = { ...

The error message "SyntaxError: Cannot use import statement outside a module" popped up while working with discord.js, typescript, heroku

// Necessary imports for running the discord bot smoothly import DiscordJS, { TextChannel, Intents, Message, Channel, NewsChannel, ThreadChannel, DiscordAPIError } from 'discord.js' type guildTextBasedChannel = TextChannel | NewsChannel | ThreadC ...

Compiling Typescript with module imports

In my project, I am working with two files named a.ts and b.ts. The interesting part is that file b exports something for file a to use. While the TypeScript compiler handles this setup perfectly, it fails to generate valid output for a browser environment ...

Looking for a SSR Component to Choose Dates?

In the process of designing a landing page, I encountered a challenge with incorporating a date picker feature. My goal is to have users select a date and then be redirected to another page upon clicking a button. The technology stack includes NextJS where ...

Utilizing the reduce() function to simultaneously assign values to two variables from data input

Looking to simplify the following function using reduce(), as the operations for variables selectedEnrolled and selectedNotEnrolled are quite similar. I attempted to use map(), but since I wasn't returning anything, it led to unintended side effects ...

Is it possible to create a tuple with additional properties without needing to cast it to any type?

To accommodate both array and object destructuring, I have defined the following `Result` type: type Errors = Record<string, string | null>; type Result = [Errors, boolean] & { errors: Errors; success: boolean }; I attempted to create a result of t ...

Implementing the ternary operator on a nested object field in typescript to enforce type validation

Is there an issue with my code or is this intentional? I want to write something similar to this. type MyDefinition = { salutation: string; value?: { typeOfValue: string; val?: string }; }; function create(name: string, input?: Partial<MyDefin ...

Adding ngrx action class to reducer registration

Looking to transition my ngrx actions from createAction to a class-based approach, but encountering an error in the declaration of the action within the associated reducer: export enum ActionTypes { LOAD_PRODUCTS_FROM_API = '[Products] Load Products ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

React.js with Typescript is throwing an error stating that a property does not exist on the child component

Currently, I am working with React in conjunction with typescript 2.3.4. I keep encountering the error TS2339: Property 'name' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'. This issue arises when attemptin ...

Encountering unexpected errors with Typescript while trying to implement a simple @click event in Nuxt 3 projects

Encountering an error when utilizing @click in Nuxt3 with Typescript Issue: Type '($event: any) => void' is not compatible with type 'MouseEvent'.ts(2322) __VLS_types.ts(107, 56): The expected type is specified in the property ' ...

The Typescript error message states that the type '{ onClick: () => void; }' cannot be assigned to the type 'IntrinsicAttributes'

I'm a beginner in Typescript and I'm encountering difficulties comprehending why my code isn't functioning properly. My goal is to create a carousel image gallery using React and Typescript. However, I'm facing issues when attempting t ...

Is there a hashing algorithm that produces identical results in both Dart and TypeScript?

I am looking to create a unique identifier for my chat application. (Chat between my Flutter app and Angular web) Below is the code snippet written in Dart... String peerId = widget.peerid; //string ID value String currentUserId = widget.currentId ...

A more concise validation function for mandatory fields

When working on an HTML application with TypeScript, I encountered a situation where I needed to build an error message for a form that had several required fields. In my TypeScript file, I created a function called hasErrors() which checks each field and ...

Inaccurate recommendations for type safety in function overloading

The TypeScript compiler is not providing accurate suggestions for the config parameter when calling the fooBar function with the 'view_product' type. Although it correctly identifies errors when an incorrect key is provided, it does not enforce t ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...

What is the best way to mandate the declaration or type of a function in TypeScript?

Let me present my dilemma: I am aiming to create a declaration file containing TypeScript function models. This file will be utilized by various individuals to build their own programs. To achieve this, I have crafted a def.d.ts file with a small example ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...

When compiling my TypeScript file, I encountered an error stating that a block-scoped variable cannot be redeclared

In my Visual Studio Code, I have written just one line of code in my ex1.ts file: let n: number = 10; Upon compiling using the command tsc ex1.ts, the compiler successfully generates the ex1.js file. However, VSC promptly displays an error in the .ts file ...

Exploring the method for obtaining parameters from a generic constructor

I have a customized class called Collection, which takes another class as a parameter named personClass. I expect the method add to accept parameters that are used in the constructor of the class User class Person { constructor(public data: object) { } ...