Snippet Vault

Browse and search through curated code snippets.

SQL

Pivot and Unpivot Patterns

SQL techniques for transforming rows to columns (pivot) and columns to rows (unpivot) for reporting and data reshaping.

sqlpivotunpivotreportingproduction-ready
Terraform

GCP Cloud Run Service

Terraform configuration for deploying a containerized service on Google Cloud Run with custom domain, VPC connector, and autoscaling.

terraformgcpcloud-runserverlessproduction-ready
Kubernetes

Pod Disruption Budget

Kubernetes PDB configurations for maintaining service availability during voluntary disruptions like node upgrades and cluster scaling.

kubernetespdbavailabilitymaintenanceproduction-ready
SQL

Materialized CTEs and Query Decomposition

Complex query decomposition using CTEs for readability, performance optimization with materialized CTEs, and query plan control.

sqlcteoptimizationreadabilityproduction-ready
Splunk

Lookup Table Enrichment

SPL patterns for enriching log data with external CSV lookups, KV store queries, and dynamic data augmentation.

splunklookupenrichmentdata-augmentationproduction-ready
Bash

Structured Log Parser

AWK-based log parsing for extracting metrics, top errors, slow requests, and generating summary reports from application logs.

bashlog-parsingawkmonitoringproduction-ready
Rust

Type-State Builder Pattern

A compile-time enforced builder using Rust's type system to guarantee required fields are set before building, with no runtime overhead.

rustdesign-patternsbuildertype-stateproduction-ready
Terraform

Remote State Management

Terraform remote state configuration with S3 backend, DynamoDB locking, cross-stack references, and state import patterns.

terraformstates3lockingproduction-ready
Kubernetes

ConfigMaps and Secrets Management

Kubernetes patterns for managing configuration with ConfigMaps, Secrets, environment variables, and volume mounts with auto-reload.

kubernetesconfigmapsecretsconfigurationproduction-ready
Go

Context Patterns

Production patterns for Go context usage including timeouts, cancellation propagation, value passing, and graceful shutdown coordination.

gocontextconcurrencycancellationproduction-ready
Splunk

Field Extraction and Enrichment

SPL patterns for extracting structured fields from unstructured logs, enriching events with lookup tables, and normalizing data.

splunkfield-extractionregexlookupproduction-ready
Go

Error Wrapping and Context

Idiomatic Go error wrapping patterns that add context at each layer while preserving the ability to inspect the original error.

goerror-handlingwrappingbest-practicesproduction-ready
GraphQL

GraphQL Subscriptions with WebSocket

Real-time GraphQL subscriptions using WebSocket transport for live data updates, with proper connection lifecycle management and authentication.

graphqlsubscriptionswebsocketreal-timeproduction-ready
React

useAsync Hook

A comprehensive async operation hook with loading/error/data states, automatic cancellation, and race condition prevention.

reacthooksasyncdata-fetchingproduction-ready
Splunk

Transaction Analysis

SPL queries for analyzing multi-event transactions including user sessions, request flows, and business process completions.

splunktransactionssession-analysisbusiness-metricsproduction-ready
Kubernetes

Canary Deployment with Traffic Splitting

Progressive canary deployment using Kubernetes with Istio traffic splitting, automated analysis, and rollback triggers.

kubernetescanaryistioprogressive-deliveryproduction-ready
Python

FastAPI Background Tasks

Patterns for running background work in FastAPI including fire-and-forget tasks, scheduled jobs, and task queues with error handling.

pythonfastapibackground-tasksasyncproduction-ready
Rust

Clone-on-Write Optimization

Using Cow (Clone on Write) for zero-copy string processing and efficient data transformation when cloning may be unnecessary.

rustperformancecowzero-copyproduction-ready
SQL

Index Strategy and Query Optimization

SQL indexing patterns for covering indexes, partial indexes, composite keys, and EXPLAIN ANALYZE interpretation for query tuning.

sqlindexingoptimizationperformanceproduction-ready
TypeScript

In-Process Pub/Sub Event Bus

A decoupled publish/subscribe event bus with async handlers, error isolation, and dead letter queue for reliable event-driven architectures.

typescriptpub-subevent-busarchitectureproduction-ready
Go

Stream Processing Pipeline

A type-safe streaming data pipeline using Go generics with composable stages, error handling, and backpressure.

gopipelinestreaminggenericsproduction-ready
Kubernetes

Liveness and Readiness Probes

Comprehensive health probe configuration for Kubernetes with startup probes, graceful shutdown, and probe-driven traffic management.

kuberneteshealth-checksprobesreliabilityproduction-ready
Python

Dataclass with Validation

Python dataclasses enhanced with runtime validation, immutability, serialization, and factory patterns for domain models.

pythondataclassvalidationdomain-modelproduction-ready
Rust

Zero-Copy Parsing

Efficient parsing patterns that reference the original input buffer without allocating, using lifetimes and slice references.

rustparsingzero-copyperformanceproduction-ready
Terraform

GKE Cluster Configuration

Google Kubernetes Engine cluster with node pools, workload identity, network policies, and cluster autoscaling.

terraformgcpgkekubernetesproduction-ready
Bash

File Watcher with Debounce

A portable file watcher that detects changes and triggers commands with debouncing to prevent rapid-fire execution.

bashfile-watcherautomationdevelopmentproduction-ready
Go

CLI Progress Bar

A terminal-friendly progress bar with ETA calculation, transfer speed display, and multi-bar support for concurrent operations.

gocliprogress-barterminalproduction-ready
Redis

Pub/Sub Event System

Redis Pub/Sub for real-time event broadcasting with pattern subscriptions, message routing, and reliable delivery patterns.

redispub-subeventsreal-timeproduction-ready
TypeScript

Circuit Breaker Pattern

A resilience pattern that prevents cascading failures by monitoring error rates and temporarily halting requests to failing services.

typescriptresiliencecircuit-breakermicroservicesproduction-ready
React

Virtualized List Component

A lightweight virtual scrolling implementation for rendering large lists efficiently by only mounting visible items in the DOM.

reactperformancevirtualizationlistsproduction-ready
Kubernetes

Blue-Green Deployment

Kubernetes blue-green deployment strategy with service switching, automated health validation, and instant rollback capability.

kubernetesblue-greendeploymentzero-downtimeproduction-ready
Python

Async Semaphore Rate Limiter

Token bucket rate limiting using asyncio semaphores for controlling throughput to external APIs with burst capacity.

pythonasyncrate-limitingsemaphoreproduction-ready
Rust

Async Streams with Tokio

Producing and consuming async data streams using async iterators, stream combinators, and bounded channel-based producers.

rustasyncstreamstokioproduction-ready
Splunk

Timechart Overlay Analysis

SPL patterns for overlaying multiple metrics on time-series charts with week-over-week comparison and trend lines.

splunktimechartvisualizationtrendsproduction-ready
TypeScript

Type-Safe Finite State Machine

A compile-time-checked state machine that prevents invalid transitions and enforces correct event handling through TypeScript's type system.

typescriptstate-machinedesign-patternsproduction-ready
React

Streaming with Nested Suspense

Nested Suspense boundaries for progressive page loading that streams critical content first while deferring non-essential sections.

reactsuspensestreamingperformanceproduction-ready
Bash

Backup Rotation Script

Automated backup with compression, rotation policies (daily/weekly/monthly), integrity verification, and S3 upload support.

bashbackupautomationsystem-administrationproduction-ready
GraphQL

DataLoader for N+1 Prevention

DataLoader pattern for batching and caching database queries in GraphQL resolvers, preventing the N+1 query problem.

graphqldataloadern-plus-oneperformanceproduction-ready
Python

Async Context Managers

Production patterns for async context managers including connection pools, distributed locks, and resource lifecycle management.

pythonasynccontext-managerresource-managementproduction-ready
Terraform

Lambda with API Gateway

Serverless API using Lambda and API Gateway v2 (HTTP API) with custom domain, stages, and IAM permissions.

terraformawslambdaapi-gatewayproduction-ready
TypeScript

Composable Middleware Chain

A type-safe middleware pipeline pattern for processing requests through ordered handlers with early termination and context passing.

typescriptmiddlewarepipelinedesign-patternsproduction-ready
Bash

GitHub Actions Matrix CI

A reusable GitHub Actions workflow with matrix builds, caching, conditional jobs, artifact handling, and deployment gates.

bashgithub-actionsci-cdautomationproduction-ready
Go

HTTP Request Validation

Declarative request validation for Go HTTP handlers using struct tags with custom validators and localized error messages.

gohttpvalidationapiproduction-ready
React

Server Actions Form Validation

Progressive enhancement form pattern using React Server Actions with Zod validation, optimistic updates, and accessible error display.

reactserver-actionsformsvalidationproduction-ready
Rust

Arc Mutex Shared State

Thread-safe shared state patterns using Arc and Mutex with lock-free alternatives, deadlock prevention, and async-compatible locking.

rustconcurrencyarc-mutexshared-stateproduction-ready
SQL

Recursive CTE Patterns

Recursive Common Table Expressions for hierarchical data, graph traversal, date series generation, and organizational trees.

sqlrecursive-ctehierarchicalgraph-traversalproduction-ready
TypeScript

Promise Pool with Concurrency Control

Execute async tasks with bounded concurrency, progress tracking, and error collection without overwhelming downstream services.

typescriptasyncconcurrencypromiseproduction-ready
Python

Streaming CSV Processing

Memory-efficient CSV processing for large files using generators, chunked reading, and parallel processing pipelines.

pythoncsvstreamingdata-processingproduction-ready
React

Server Component Data Fetching

Patterns for data fetching in React Server Components with parallel loading, error handling, caching, and streaming with Suspense.

reactserver-componentsdata-fetchingnextjsproduction-ready
Splunk

Correlation Search Patterns

SPL queries that correlate events across multiple data sources for incident investigation and root cause analysis.

splunkcorrelationincident-responseinvestigationproduction-ready
TypeScript

Token Bucket Rate Limiter

An in-memory token bucket rate limiter with sliding window support for API endpoint protection and request throttling.

typescriptrate-limitingapisecurityproduction-ready
Bash

Disk Usage Monitor

Automated disk monitoring with threshold alerts, growth rate tracking, and capacity forecast for proactive storage management.

bashmonitoringdiskalertingproduction-ready
Rust

Error Context with anyhow

Application-level error handling using anyhow for rich error context chains, downcasting, and integration with thiserror domain errors.

rusterror-handlinganyhowcontextproduction-ready
Go

Structured Custom Errors

Production error handling patterns with sentinel errors, wrapped context, error types, and structured error responses for APIs.

goerror-handlingapistructured-errorsproduction-ready
GraphQL

GraphQL Schema Design

Production GraphQL schema with union types, interfaces, pagination, input validation, custom directives, and error handling.

graphqlschemaapi-designtypesproduction-ready
React

Render Props with TypeScript

A flexible render props pattern for sharing stateful logic between components, with full type inference for the render function arguments.

reactpatternsrender-propstypescriptproduction-ready
Kubernetes

Init Containers Pattern

Kubernetes init containers for database migrations, config loading, dependency waiting, and secret provisioning before app startup.

kubernetesinit-containersstartupmigrationsproduction-ready
Python

Pandas Pivot Table Analysis

Advanced pivot table patterns for multi-dimensional data analysis with custom aggregations, margins, and formatting.

pythonpandasdata-analysispivot-tableproduction-ready
React

Error Boundary with Recovery

A production React error boundary with error reporting, retry logic, fallback UI, and integration with error tracking services.

reacterror-boundaryerror-handlingresilienceproduction-ready
Rust

CLI with Clap Derive

A production CLI application using clap's derive macros for type-safe argument parsing with subcommands, validation, and help generation.

rustcliclapderiveproduction-ready
Terraform

ECS Fargate Service

Terraform configuration for deploying a containerized service on AWS ECS Fargate with ALB, auto-scaling, and CloudWatch logging.

terraformawsecsfargateproduction-ready
TypeScript

Runtime Schema Validation with Zod

Type-safe runtime validation patterns using Zod for API request/response validation with automatic TypeScript type inference.

typescriptvalidationzodapiproduction-ready
Splunk

Threshold-Based Alerting

SPL alert queries with multi-condition thresholds, alert deduplication, severity classification, and runbook links.

splunkalertingthresholdsmonitoringproduction-ready
TypeScript

Lightweight Dependency Injection Container

A type-safe DI container with constructor injection, singleton/transient scoping, and lazy resolution for modular architectures.

typescriptdependency-injectionarchitectureproduction-ready
Bash

Docker Build and Push Pipeline

CI/CD script for building multi-platform Docker images with layer caching, vulnerability scanning, and registry push.

bashdockerci-cdcontainerproduction-ready
Go

Fan-Out/Fan-In Pipeline

A composable pipeline pattern with fan-out for parallel stage processing and fan-in to merge results from multiple goroutines.

goconcurrencypipelinefan-outproduction-ready
Redis

Cache-Aside Pattern

Redis cache-aside implementation with TTL, cache stampede prevention, cache warming, and invalidation strategies for read-heavy workloads.

rediscachingcache-asideperformanceproduction-ready
TypeScript

Result Type for Error Handling

A Rust-inspired Result type for TypeScript that makes errors part of the type system instead of relying on try/catch.

typescripterror-handlingresult-typefunctionalproduction-ready
Python

Execution Timing Decorator

A flexible timing decorator that captures execution duration, emits metrics, supports async functions, and integrates with logging.

pythondecoratormonitoringperformanceproduction-ready
React

Compound Components Pattern

A React pattern for building flexible, implicitly shared-state component APIs like Tabs, Accordion, and Select using context.

reactpatternscompound-componentscompositionproduction-ready
Docker

Multi-Stage Docker Build

Production Dockerfile with multi-stage builds for minimal image size, security hardening, non-root users, and health checks.

dockermulti-stageoptimizationsecurityproduction-ready
Rust

Tokio Select for Async Control Flow

Patterns for concurrent async operations using tokio::select! with cancellation, timeouts, and graceful shutdown coordination.

rustasynctokioselectproduction-ready
SQL

Window Functions Patterns

Advanced SQL window functions for running totals, rankings, lag/lead analysis, and moving averages without self-joins.

sqlwindow-functionsanalyticsperformanceproduction-ready
TypeScript

Typed EventEmitter for Node.js

Extend Node.js EventEmitter with full TypeScript type safety for event names and listener signatures.

typescriptnodejseventstype-safetyproduction-ready
Go

Table-Driven Tests Pattern

Idiomatic Go testing with table-driven test cases, subtests, parallel execution, and custom test helpers for comprehensive coverage.

gotestingtable-drivenbest-practicesproduction-ready
Python

TTL Cache Decorator

A time-based cache decorator with configurable TTL, max size, and key generation for expensive function calls.

pythondecoratorcachingperformanceproduction-ready
Bash

Service Health Check Script

A comprehensive health checking script that monitors HTTP endpoints, TCP ports, disk space, and service dependencies with alerting.

bashmonitoringhealth-checkautomationproduction-ready
React

useMediaQuery Hook

A SSR-safe React hook for responsive design that tracks CSS media query matches and triggers re-renders on breakpoint changes.

reacthooksresponsivemedia-queryproduction-ready
Splunk

Anomaly Detection Queries

SPL patterns for detecting anomalous behavior including sudden traffic spikes, unusual error patterns, and baseline deviation alerts.

splunkanomaly-detectionalertingstatisticsproduction-ready
TypeScript

Worker Thread Pool

A managed pool of Node.js worker threads with task queuing, error recovery, and automatic scaling for CPU-intensive operations.

typescriptnodejsworker-threadsconcurrencyproduction-ready
Python

FastAPI Dependency Injection

Advanced dependency injection patterns for FastAPI with database sessions, authentication, caching, and hierarchical dependencies.

pythonfastapidependency-injectiondatabaseproduction-ready
TypeScript

Node.js Stream Pipeline

Type-safe stream pipeline utility for processing large files with backpressure handling, error propagation, and progress tracking.

typescriptnodejsstreamsbackpressureproduction-ready
Python

Configurable Retry Decorator

A decorator for retrying failed operations with exponential backoff, jitter, exception filtering, and callback hooks.

pythondecoratorretryresilienceproduction-ready
Go

HTTP Middleware Chain

Composable middleware pattern for Go HTTP servers with logging, recovery, auth, rate limiting, and request ID propagation.

gohttpmiddlewarewebproduction-ready
Kubernetes

Horizontal Pod Autoscaler

Kubernetes HPA configuration with CPU/memory metrics, custom metrics, scaling behavior tuning, and stabilization windows.

kubernetesautoscalinghpascalingproduction-ready
React

Custom useForm Hook

A lightweight form management hook with field-level validation, touched tracking, and submit handling without external dependencies.

reacthooksformsvalidationproduction-ready
Python

Async Gather with Error Handling

Patterns for running concurrent async tasks with proper error collection, timeouts, semaphore-based rate limiting, and partial results.

pythonasyncconcurrencyerror-handlingproduction-ready
Splunk

Service Health Dashboard

SPL queries for monitoring service health including uptime, error rates, response times, and availability SLI calculations.

splunkmonitoringdashboardsliproduction-ready
TypeScript

Fluent Builder Pattern

A type-safe builder pattern using method chaining with conditional required fields enforced at compile time.

typescriptdesign-patternsbuilderproduction-ready
Bash

Parallel Task Execution

Shell patterns for running multiple tasks in parallel with job control, progress tracking, error collection, and result aggregation.

bashparallelconcurrencyautomationproduction-ready
Go

Concurrent Worker Pool

A generic worker pool pattern using goroutines and channels for bounded parallel processing with graceful shutdown.

goconcurrencyworker-poolchannelsproduction-ready
TypeScript

Type-Safe Observer Pattern

A generic event emitter with full type inference for event names and payload types, supporting once listeners and wildcard subscriptions.

typescriptdesign-patternsobservereventsproduction-ready
React

useIntersectionObserver Hook

A React hook for detecting element visibility with configurable thresholds, enabling lazy loading, infinite scroll, and scroll-triggered animations.

reacthooksintersection-observerperformanceproduction-ready
Rust

Custom Errors with thiserror

Production error handling using thiserror for deriving Error implementations with automatic From conversions and context propagation.

rusterror-handlingthiserrorproduction-ready
Python

FastAPI Request Middleware

Production middleware for FastAPI with request ID injection, timing, structured logging, and CORS configuration.

pythonfastapimiddlewareloggingproduction-ready
Terraform

AWS VPC Module

A reusable Terraform module for creating a production VPC with public/private subnets, NAT gateways, and flow logs across multiple AZs.

terraformawsvpcnetworkingproduction-ready
TypeScript

Type-Safe Singleton Pattern

A modern TypeScript singleton implementation using private constructors and lazy initialization for service instances.

typescriptdesign-patternssingletonproduction-ready
TypeScript

Retry with Exponential Backoff

A configurable async retry utility with exponential backoff, jitter, and abort signal support for resilient API calls.

typescriptasyncretryresilienceproduction-ready
React

useLocalStorage Hook

A type-safe React hook that syncs state with localStorage, handles serialization, and supports cross-tab synchronization via storage events.

reacthookslocalStoragepersistenceproduction-ready
TypeScript

Exhaustive Type Guards

Type-safe discriminated union handling with exhaustive checking to catch missing cases at compile time.

typescripttype-guardsdiscriminated-unionsproduction-ready
TypeScript

Type-Safe Deep Clone

A recursive deep clone utility with full TypeScript type preservation, handling Date, RegExp, Map, Set, and circular references.

typescriptutilitydeep-cloneproduction-ready
GitHub Actions

Monorepo Path-Filtered CI

GitHub Actions workflow with path-based filtering, matrix strategy for affected packages, dependency caching, and conditional deployment steps.

github-actionsci-cdmonorepoautomationproduction-ready
SQL

Recursive Org Chart Query

PostgreSQL recursive CTE that traverses hierarchical data (org charts, category trees, threaded comments) with depth limiting and cycle detection.

sqlpostgresqlrecursive-ctehierarchical-dataproduction-ready
Elasticsearch

Fuzzy Multi-Field Search

Elasticsearch query DSL for fuzzy full-text search across multiple fields with boosting, highlighting, suggestions, and custom analyzers.

elasticsearchsearchfull-textfuzzy-matchingproduction-ready
Next.js

Server Action Form with Zod Validation

Type-safe Next.js server action with Zod schema validation, error handling, and a progressive enhancement form component.

next-jsserver-actionszodformsvalidationproduction-ready
Rust

Token Bucket Rate Limiter

Thread-safe token bucket rate limiter using Arc and Mutex with configurable refill rate, burst capacity, and async support via Tokio.

rustconcurrencyrate-limitingtokioproduction-ready
React

Optimistic UI with useOptimistic

React 19 useOptimistic hook pattern for instant UI feedback during async form submissions with automatic rollback on failure.

react-19hooksoptimistic-uiformsproduction-ready
Redis

Distributed Lock with Redlock

Implementation of the Redlock algorithm for distributed mutual exclusion across multiple Redis instances with automatic TTL expiry and retry logic.

redisdistributed-systemslockingtypescriptproduction-ready
Splunk

Deployment Event Correlation

SPL query that correlates deployment events with error rate changes to identify regressions introduced by releases.

splunk-clouddeploymentscorrelationerror-ratesproduction-ready
Swift

Async Image Cache with LRU

Actor-based async image downloading and caching system using URLSession, NSCache with LRU eviction, disk persistence, and memory pressure handling for iOS apps.

swiftioscachingasync-awaitproduction-ready
Go

Graceful HTTP Server Shutdown

Go HTTP server with signal handling, graceful connection draining, and context-based timeout for zero-downtime deployments.

gohttpgraceful-shutdownsignalsproduction-ready
Bash

Git Pre-commit Hook Installer

Shell script that installs and configures pre-commit hooks for linting, formatting, and type checking with automatic dependency detection.

gitpre-commitdevopslintingautomationdeveloper-experience
Splunk

Aggregate Errors by Source

A Splunk SPL query that aggregates error events by source and displays the top offenders over the last 24 hours.

splunkmonitoringerror-trackingproduction-ready
Splunk

Latency Percentiles by Service

SPL query for calculating latency percentiles (p50, p95, p99) grouped by service name, with trend analysis over time.

splunk-cloudobservabilitylatencypercentilesproduction-ready
Kubernetes

Zero-Downtime Rolling Deployment

Complete K8s deployment manifest with readiness/liveness probes, pod disruption budget, rolling update strategy, and resource limits.

kubernetesdeploymentzero-downtimecontainersproduction-ready
Bash

Docker Healthcheck Script

Multi-endpoint Docker healthcheck script that verifies service readiness by checking HTTP endpoints, TCP ports, and database connectivity.

dockerhealthcheckdevopscontainersproduction-ready
Bash

Log File Rotator

A Bash script that rotates log files older than 7 days by compressing and archiving them to a backup directory.

bashdevopsloggingautomationproduction-ready
Python

Retry Decorator with Backoff

Configurable retry decorator with exponential backoff, jitter, and exception filtering for resilient Python applications.

pythondecoratorretryexponential-backoffresilienceproduction-ready
CSS

Fluid Typography Scale

Modern CSS clamp()-based fluid typography system with custom properties, modular scale, and responsive spacing that eliminates breakpoint jumps.

csstypographyresponsive-designcustom-propertiesproduction-ready
Python

Async API Client with Retry

Production-ready async HTTP client using aiohttp with automatic retry, session management, and structured error handling.

pythonasyncaiohttpretryapi-clientproduction-ready
Python

Batch Text Summarizer

A Python script that reads text files from a directory and generates concise summaries using a local transformer model.

pythonaitransformersbatch-processingnlp
Terraform

Multi-Environment Module Pattern

Reusable Terraform module with environment-specific variable files, remote state configuration, and workspace isolation.

terraforminfrastructure-as-codemodulesmulti-environmentproduction-ready
React

useDebounce Hook

A custom React hook that debounces a value by a specified delay, useful for search inputs and API calls.

reacthooksperformanceproduction-readyreact-19