Code Explainers

Browse the library

rust
use std::any::{Any, TypeId};
use std::collections::HashMap;
 
pub trait Event: Any {

A type-safe event bus in Rust

type-erasure trait-objects downcasting
Advanced 8 steps
php
<?php
 
namespace App\Models;
 

How Eloquent scopes model order status in Laravel

query scopes state machine eloquent
Intermediate 7 steps
java
@RestController
@RequestMapping("/api/reports")
public class OrderReportController {
 

Streaming a CSV export in Spring

streaming csv-export backpressure
Intermediate 9 steps
ruby
class Article < ApplicationRecord
  belongs_to :author, class_name: "User"
  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings

How scopes compose in Rails

scopes activerecord query-composition
Intermediate 8 steps
python
import json
import hashlib
from datetime import timedelta
 

Idempotent payment endpoints in FastAPI

idempotency redis distributed-locking
Advanced 9 steps
typescript
type QueuedRequest = {
  id: string;
  url: string;
  method: string;

A retry queue with exponential backoff

retry exponential-backoff persistence
Intermediate 10 steps
ruby
class Order
  class InvalidTransition < StandardError; end
 
  TRANSITIONS = {

A state machine for order transitions in Ruby

state-machine data-driven error-handling
Intermediate 8 steps
python
from flask import Blueprint, jsonify, request, abort
 
v1 = Blueprint("users_v1", __name__)
v2 = Blueprint("users_v2", __name__)

Versioning a Flask API with Blueprints

api versioning blueprints rest
Intermediate 7 steps
java
public class SlidingLogRateLimiter {
 
    private final int maxRequests;
    private final long windowMillis;

How a sliding-log rate limiter works

rate-limiting concurrency sliding-window
Advanced 8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

How a JWT strategy authenticates in NestJS

authentication jwt passport
Intermediate 7 steps
go
package theme
 
import (
	"fmt"

Per-tenant HTML templates with Gin's renderer

multi-tenancy concurrency html-templates
Advanced 8 steps
rust
use std::cmp::Ordering;
 
pub struct PrefixIndex {
    entries: Vec<String>,

Prefix search with binary partitioning in Rust

binary-search sorting case-insensitive
Intermediate 7 steps
php
<?php
 
namespace App\Http\Controllers;
 

Streaming a filtered CSV export in Laravel

streaming csv-export query-builder
Intermediate 9 steps
javascript
const express = require('express');
const router = express.Router();
const { pool } = require('../db');
const redis = require('../redis');

Building a health check endpoint in Express

health-check timeouts promise-race
Intermediate 9 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1]
  def change
    create_table :order_items do |t|
      t.references :order, null: false, foreign_key: { on_delete: :cascade }

Enforcing order-item integrity in Rails

migrations foreign-keys validations
Intermediate 7 steps
python
import time
import threading
from enum import Enum
from functools import wraps

Building a circuit breaker in Python

circuit-breaker resilience decorators
Advanced 7 steps
java
public final class Slugifier {
 
    private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]");
    private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");

Building a URL slugifier in Java

regex unicode-normalization string-processing
Intermediate 8 steps
typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { catchError, filter, take, switchMap } from 'rxjs/operators';

Refreshing auth tokens in an Angular interceptor

http-interceptor token-refresh rxjs
Advanced 8 steps