Skip to content

jedisct1/ratelimit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rate Limiter

A lightweight C library for implementing rate limiting in applications using the Count-Min Sketch algorithm. This library efficiently tracks IP addresses and determines when they exceed a specified request rate threshold.

How It Works

The library uses a Count-Min Sketch data structure with the following approach:

  1. IP addresses are hashed to two positions in a fixed-size array using SipHash-2-4
  2. Each hit increments counters at both positions
  3. When checking if an IP should be rate-limited, the minimum of the two counters is used
  4. Counters automatically decay over time to prevent indefinite growth

Installation

Simply copy the ratelimit.h and ratelimit.c files into your project, or compile as a library.

Usage

Basic Example

#include "ratelimit.h"
#include <netinet/in.h>

int main() {
    RateLimiter rl;
    unsigned char key[16] = {0}; // Should be random in real usage

    // Initialize with 1024 slots and 2048 period
    if (ratelimiter_init(&rl, 1024, 2048, key) != 0) {
        return -1; // Error
    }

    struct sockaddr_in client_addr;
    client_addr.sin_family = AF_INET;
    client_addr.sin_addr.s_addr = inet_addr("192.168.1.100");

    // Check if client should be rate limited (more than 100 requests)
    int result = ratelimiter_hit(&rl, (struct sockaddr*)&client_addr, 100);

    if (result > 0) {
        // Client should be rate limited
        printf("Rate limiting this client\n");
    } else if (result == 0) {
        // Client is under the limit
        printf("Request allowed\n");
    }

    ratelimiter_free(&rl);
    return 0;
}

Compilation

To compile with your application:

gcc -Wall -Wextra -o your_app your_app.c ratelimit.c

To compile and run the included test:

gcc -Wall -Wextra -o test_simple test_simple.c ratelimit.c
./test_simple

API Reference

See ratelimit.h for full API documentation:

  • ratelimiter_init(): Initialize a new rate limiter
  • ratelimiter_free(): Free resources used by a rate limiter
  • ratelimiter_hit(): Record a hit and check if rate limit is exceeded
  • ratelimiter_rekey(): Change the hash key to redistribute entries

About

Plug-and-play IP rate limiter in C

Topics

Resources

License

Stars

26 stars

Watchers

1 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages