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.
The library uses a Count-Min Sketch data structure with the following approach:
- IP addresses are hashed to two positions in a fixed-size array using SipHash-2-4
- Each hit increments counters at both positions
- When checking if an IP should be rate-limited, the minimum of the two counters is used
- Counters automatically decay over time to prevent indefinite growth
Simply copy the ratelimit.h and ratelimit.c files into your project, or compile as a library.
#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;
}To compile with your application:
gcc -Wall -Wextra -o your_app your_app.c ratelimit.cTo compile and run the included test:
gcc -Wall -Wextra -o test_simple test_simple.c ratelimit.c
./test_simpleSee ratelimit.h for full API documentation:
ratelimiter_init(): Initialize a new rate limiterratelimiter_free(): Free resources used by a rate limiterratelimiter_hit(): Record a hit and check if rate limit is exceededratelimiter_rekey(): Change the hash key to redistribute entries