Skip to content

Instantly share code, notes, and snippets.

@david-a-perez
david-a-perez / fastest_day6_part2.rs
Last active February 22, 2024 00:26
Advent of Code 2023 Day 6 Optimizations
// time: [1.8843 µs 1.8897 µs 1.8955 µs]
pub fn original(input: &[u8]) -> Option<usize> {
let mut idx = 0;
'outer: while idx + 13 < input.len() {
let mut state = 0;
for (next_idx, byte) in input[idx..idx + 14].iter().enumerate().rev() {
let bit_idx = byte % 32;
if state & (1 << bit_idx) != 0 {
idx += next_idx + 1;
continue 'outer;

Scaling your API with rate limiters

The following are examples of the four types rate limiters discussed in the accompanying blog post. In the examples below I've used pseudocode-like Ruby, so if you're unfamiliar with Ruby you should be able to easily translate this approach to other languages. Complete examples in Ruby are also provided later in this gist.

In most cases you'll want all these examples to be classes, but I've used simple functions here to keep the code samples brief.

Request rate limiter

This uses a basic token bucket algorithm and relies on the fact that Redis scripts execute atomically. No other operations can run between fetching the count and writing the new count.

@jboner
jboner / latency.txt
Last active June 14, 2024 16:15
Latency Numbers Every Programmer Should Know
Latency Comparison Numbers (~2012)
----------------------------------
L1 cache reference 0.5 ns
Branch mispredict 5 ns
L2 cache reference 7 ns 14x L1 cache
Mutex lock/unlock 25 ns
Main memory reference 100 ns 20x L2 cache, 200x L1 cache
Compress 1K bytes with Zippy 3,000 ns 3 us
Send 1K bytes over 1 Gbps network 10,000 ns 10 us
Read 4K randomly from SSD* 150,000 ns 150 us ~1GB/sec SSD