concurrency

python
import functools
import threading


def debounce(wait):
    def decorator(func):

Debounce Repeated Function Calls With a Thread-Safe Python Decorator

python decorators debounce
by codesnips 2 tabs
rust
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};

#[derive(Default)]
struct Metrics {
    per_endpoint: HashMap<String, u64>,

Thread-Safe Request Metrics with Arc, Mutex, and a Poison-Recovery Guard

rust concurrency arc
by codesnips 3 tabs
typescript
import { Pool } from "pg";

async function keyFor(pool: Pool, name: string): Promise<string> {
  const { rows } = await pool.query<{ key: string }>(
    "SELECT hashtextextended($1, 0) AS key",
    [name]

Postgres advisory lock for one-at-a-time work

postgres concurrency reliability
by codesnips 3 tabs
rust
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(async {
        sleep(Duration::from_millis(100)).await;

tokio::spawn for concurrent task execution

rust async tokio
by Marcus Chen 1 tab
ruby
class Order < ApplicationRecord
  include TransactionalEnqueue

  belongs_to :customer
  has_many :line_items, dependent: :destroy

Transaction-Safe After-Commit Hook (Avoid Ghost Jobs)

rails activerecord background-jobs
by codesnips 4 tabs
javascript
class TokenBucket {
  constructor(capacity, refillRatePerSec) {
    this.capacity = capacity;
    this.refillRate = refillRatePerSec;
    this.tokens = capacity;
    this.lastRefill = Date.now();

Token Bucket Rate Limiter as Express Middleware

express rate-limiting token-bucket
by codesnips 3 tabs
go
package scheduler

import (
	"context"
	"log"
	"sync"

Graceful Cron-Style Scheduler in Go With Ticker and Context Cancellation

scheduler ticker context
by codesnips 3 tabs
ruby
require "securerandom"
require "digest"

class SlidingWindowLimiter
  Result = Struct.new(:allowed, :count, :remaining)

Sliding-Window API Rate Limiting with Rack Middleware and Redis

ruby rack redis
by codesnips 4 tabs
sql
-- Step 1: add the column nullable, no default.
-- Catalog-only change in Postgres 11+, returns instantly.
ALTER TABLE orders
  ADD COLUMN currency text;

-- Optional: keep the lock attempt bounded so a long-running

SQL migration safety: add column nullable, backfill, then constrain

postgres migrations reliability
by codesnips 3 tabs
go
package middleware

import (
  "net/http"
  "sync/atomic"
)

Track in-flight requests with atomic counters

go observability concurrency
by Leah Thompson 1 tab
python
import threading


class MinuteRingBuffer:
    def __init__(self, window_minutes=15):
        if window_minutes < 1:

Rolling Per-Minute Log Aggregation with a Ring Buffer

logging metrics observability
by codesnips 3 tabs
ruby
class LeaderboardCache
  TOP_KEY = "leaderboard:top".freeze
  STATS_KEY = "leaderboard:stats".freeze

  def top_players
    Rails.cache.fetch(TOP_KEY, expires_in: 5.minutes, race_condition_ttl: 15.seconds) do

Cache Stampede Protection with race_condition_ttl

rails caching performance
by codesnips 3 tabs