concurrency

ruby
class PresenceRegistry
  TTL = 30 # seconds a user counts as present without a heartbeat

  def initialize(room_id, redis: REDIS)
    @room_id = room_id
    @redis = redis

Action Cable Presence Tracking (Lightweight)

rails actioncable redis
by codesnips 3 tabs
php
<?php

namespace App\Jobs;

use App\Models\Invoice;
use App\Services\StripeGateway;

Preventing Double-Charges in Laravel with WithoutOverlapping Job Middleware

laravel queues background-jobs
by codesnips 3 tabs
ruby
class AddLockVersionToPosts < ActiveRecord::Migration[6.1]
  def change
    add_column :posts, :lock_version, :integer, default: 0, null: false
  end
end

Optimistic locking for concurrent updates

rails database concurrency
by Alex Kumar 2 tabs
ruby
class Task < ApplicationRecord
  POSITION_GAP = 1024

  belongs_to :board

  scope :ordered, -> { order(:position) }

Reorder a list server-side and reflect instantly with Turbo Streams

rails hotwire turbo
by codesnips 4 tabs
lua
-- KEYS[1] = bucket key
-- ARGV[1] = capacity, ARGV[2] = refill_rate (tokens/sec)
-- ARGV[3] = now_ms, ARGV[4] = requested tokens
local capacity    = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now_ms      = tonumber(ARGV[3])

Token Bucket Rate Limiting in a Servlet Filter with Redis and Lua

rate-limiting token-bucket servlet
by codesnips 3 tabs
ruby
class SlidingWindowLimiter
  Result = Struct.new(:allowed, :count, :limit, :window_ms, keyword_init: true)

  SCRIPT = <<~LUA.freeze
    local key = KEYS[1]
    local now = tonumber(ARGV[1])

Rate Limiting with Redis + Increment Expiry

rails redis reliability
by codesnips 3 tabs
ruby
class DebouncedReindexJob
  include Sidekiq::Job

  sidekiq_options queue: :indexing, retry: 5

  DEBOUNCE_DELAY = 5 # seconds

Debouncing Sidekiq Jobs Per-Record With Redis So Rapid Updates Coalesce Into One Run

rails sidekiq redis
by codesnips 3 tabs
rust
use dashmap::DashMap;
use std::time::Instant;

pub struct TokenBucket {
    tokens: f64,
    last_refill: Instant,

Token-Bucket Rate Limiter Middleware for Axum Using DashMap

axum rust rate-limiting
by codesnips 3 tabs
javascript
class BatchLoader {
  constructor(batchFn, { cacheKeyFn = (k) => k } = {}) {
    this.batchFn = batchFn;
    this.cacheKeyFn = cacheKeyFn;
    this.cache = new Map();
    this.queue = [];

Coalescing Concurrent Reads with a DataLoader-Style Batch Loader in Node

dataloader batching graphql
by codesnips 3 tabs
rust
use tokio::sync::broadcast;

pub struct Shutdown {
    is_shutdown: bool,
    notify: broadcast::Receiver<()>,
}

Graceful Shutdown for a Tokio TCP Server on Ctrl-C with a Broadcast Signal

tokio async graceful-shutdown
by codesnips 3 tabs
ruby
class InventoryLevel < ApplicationRecord
  belongs_to :warehouse

  UPSERT_COLUMNS = %w[warehouse_id sku on_hand reserved updated_at].freeze

  def self.upsert_counts(rows)

Bulk-Upsert Inventory Counts in One Query From a Sidekiq Job

rails postgres upsert
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  class InvalidTransition < StandardError; end

  enum status: { pending: 0, paid: 1, shipped: 2, cancelled: 3 }

  has_many :order_transitions, -> { order(:created_at) }, dependent: :destroy

Order State Machine With Guarded Transitions and an Audit Trail in Rails

rails state-machine activerecord
by codesnips 3 tabs