Code Explainers

Browse the library

javascript
import { NextResponse } from 'next/server';
import { Redis } from '@upstash/redis';
 
const redis = Redis.fromEnv();

Sliding-window rate limiting in a Next.js route

rate-limiting redis sorted-set
Advanced 8 steps
python
from flask import Blueprint, jsonify
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
 

Building a health check endpoint in Flask

health-check blueprint error-handling
Intermediate 6 steps
java
@Component
public class RegionCacheWarmer implements SmartInitializingSingleton {
 
    private static final Logger log = LoggerFactory.getLogger(RegionCacheWarmer.class);

Warming a Spring cache at startup

caching startup-hook dependency-injection
Intermediate 7 steps
typescript
import { Controller, Param, Sse, MessageEvent } from '@nestjs/common';
import { Observable, interval, merge } from 'rxjs';
import { filter, map, takeWhile } from 'rxjs/operators';
import { JobService } from './job.service';

Streaming job progress with SSE in NestJS

server-sent-events reactive-streams rxjs
Intermediate 8 steps
go
package breaker
 
import (
	"errors"

How a circuit breaker works in Go

circuit-breaker state-machine concurrency
Intermediate 8 steps
php
<?php
 
final class TaskProgressReporter
{

Tracking task progress in a JSON file

state-persistence atomic-writes json
Intermediate 9 steps
ruby
class WebhookSignatureConstraint
  def initialize(provider)
    @provider = provider
  end

Verifying webhook signatures with Rails routing constraints

routing constraints hmac webhooks
Advanced 7 steps
rust
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
    Number(f64),
    Plus,

How a tokenizer turns text into tokens

lexing enums iterators
Intermediate 8 steps
javascript
const MAX_FILE_SIZE = 5 * 1024 * 1024;
 
const ALLOWED_TYPES = {
  'image/jpeg': ['jpg', 'jpeg'],

Validating file uploads by content, not just claims

input-validation security magic-bytes
Intermediate 7 steps
python
import pandas as pd
import numpy as np
 
 

Cleaning a customer DataFrame with pandas

data-cleaning regex normalization
Intermediate 9 steps
java
public final class EmailNormalizer {
 
    private static final Pattern EMAIL_PATTERN = Pattern.compile(
        "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"

Normalizing email addresses in Java

validation regex normalization
Intermediate 8 steps
typescript
import {
  Controller,
  All,
  Req,

Catch-all routes and error shaping in NestJS

exception-handling routing middleware
Intermediate 6 steps
ruby
module UniqueJob
  extend ActiveSupport::Concern
 
  class_methods do

Deduplicating Active Job enqueues in Rails

concurrency idempotency caching
Advanced 9 steps
rust
use axum::{
    extract::{FromRequestParts, Host},
    http::{request::Parts, StatusCode},
};

Multi-tenant DB routing in Axum extractors

multi-tenancy extractors connection-pooling
Advanced 8 steps
javascript
function zip(keys, values) {
  if (keys.length !== values.length) {
    throw new RangeError('zip expects arrays of equal length');
  }

Three ways to zip arrays in JavaScript

arrays higher-order-functions pairing
Intermediate 6 steps
python
from datetime import date, timedelta
from typing import Annotated
 
from fastapi import APIRouter, Depends, Query

Validating date ranges with FastAPI dependencies

dependency-injection validation pydantic
Intermediate 6 steps
java
@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
public class ProductBatchController {

Batch JSON Merge Patch in Spring

json-merge-patch rest-api partial-update
Intermediate 8 steps
typescript
import {
  ArgumentsHost,
  Catch,
  ConflictException,

Turning TypeORM lock errors into 409s in NestJS

exception-handling optimistic-locking http-status
Intermediate 6 steps