concurrency

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
ruby
class AddSlugToArticles < ActiveRecord::Migration[7.1]
  def change
    add_column :articles, :slug, :string, null: false, default: ""
    add_index :articles, :slug, unique: true

    # Backfill existing rows before the unique index is relied upon in code.

Generate Unique URL Slugs in Rails with before_validation and a friendly Controller Lookup

rails activerecord slugs
by codesnips 3 tabs
python
import datetime as dt

from sqlalchemy import Column, DateTime, Integer, String, UniqueConstraint
from sqlalchemy.orm import declarative_base

Base = declarative_base()

Idempotent Webhook Ingestion With a Postgres Dedupe Store in FastAPI

fastapi webhooks idempotency
by codesnips 3 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
python
from datetime import datetime
from app.extensions import db


class IdempotencyKey(db.Model):
    __tablename__ = "idempotency_keys"

Idempotency-Key Deduplication for POST Requests in a Flask Blueprint

flask idempotency postgres
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
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Optimistic Locking With a Version Column in Laravel Eloquent

laravel eloquent optimistic-locking
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
java
package com.shop.payments.messaging;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public record PaymentEvent(

Idempotent Kafka Consumer With @KafkaListener and Manual Ack in Spring Boot

spring-boot kafka spring-kafka
by codesnips 3 tabs