Useful engineering, in one place.
Essays, code patterns, research notes, and stories about the systems behind real products. Start with a problem; follow the links as deep as you need.
185 resources
- OtherWho Is Ayush Basak? CTO, Systems Architect and EngineerAyush Basak is a CTO and systems architect in Kolkata who builds backend platforms, database systems, distributed infrastructure, and production AI products.
- OtherAI Systems EngineeringLearn how to design production AI systems around evidence, evaluation, bounded authority, observability, cost, and safe failure.
- OtherAI Notes - Ayush BasakPapers, experiments, and practical notes on building dependable AI systems
- OtherLife Is Beyond BinaryHow someone who once hated Computer Science became obsessed with systems—and the person who made that possible.
- Research & booksBookshelf - Ayush BasakEngineering and systems books with applied takeaways
- OtherChangelog — AyushworksMeaningful changes to Ayush Basak's public engineering notebook, technical tools, writing, and product experiments.
- OtherConnect with Ayush BasakFind Ayush Basak on LinkedIn, X, YouTube and GitHub, or get in touch by email. All my links in one place.
- OtherContact Ayush BasakContact Ayush Basak about CTO leadership, systems architecture, backend platforms, database engineering, or production AI systems.
- OtherCTO & Systems Architect in Kolkata — Ayush BasakAyush Basak is a hands-on CTO and systems architect in Kolkata building backend platforms, database systems, distributed infrastructure, and production AI.
- OtherDatabase Engineer — PostgreSQL, Data Models and Reliable BackendsDatabase engineering by Ayush Basak: PostgreSQL, data modelling, indexing, migrations, concurrency, observability, and reliable backend architecture.
- OtherCopyright and DMCA PolicyHow to report copyright infringement on ayushworks.xyz, what a complete notice should contain, and how corrections or counter-notices are handled.
- Research & booksEngineering notesShort engineering takeaways, failure boundaries, and tests.
- Field notesThe Hardware Did Not Read the API ContractTiming, partial truth, and designing software around a physical system that cannot be rolled back.
- OtherField Notes — Product, Engineering, and Leadership StoriesHonest stories from Ayush Basak about products, production failures, imperfect engineering, management decisions, and the people inside the systems.
- Field notesSupport Needed a Truthful Answer, Not Another DashboardTurning an ambiguous asynchronous operation into a supportable product contract.
- Field notesThe Architecture Is Not the ProductA field note on choosing engineering boundaries for Saleslyt, Myotrek, healthcare services, and offline payments—and why the real constraint matters more than the impressive diagram.
- Field notesThe Best Fix Deleted a WorkflowWe stopped automating an accidental process and removed the reason it existed.
- Field notesThe Dashboard Was Green. The Customer Was Stuck.Why component health is not product health, and how to rebuild observability around a customer operation.
- Field notesThe Demo That Changed the RoadmapDiscovering that correct software was answering the wrong question—and changing the roadmap before adding more machinery.
- Field notesThe Feature Flag Had No OwnerA temporary rollout control became permanent production state because nobody owned its removal.
- Field notesThe Incident Needed an Owner, Not Another ChannelReducing coordination load, separating command from investigation, and making decisions reversible under pressure.
- Field notesThe Microservice We Chose Not to BuildPreserving a domain boundary without paying for an independent service too early.
- Field notesThe Migration Was Safe Until We Needed RollbackA schema change passed forward tests but exposed that rollback was never part of the design.
- Field notesWe Made the Worker Faster and the Product SlowerA throughput improvement moved the bottleneck downstream and made the customer experience worse.
- OtherLife Is Beyond BinaryHow someone who once hated Computer Science became obsessed with systems—and the person who made that possible.
- OtherHardware Engineering Knowledge Base — Ayush BasakPractical explanations of hardware interfaces, firmware boundaries, and device debugging. Start with USB enumeration, endpoints, and transfers.
- OtherAyush Basak — CTO, Systems Architect, and EngineerAyush Basak builds backend platforms, database systems, distributed infrastructure, and production AI—and publishes the reasoning behind the work.
- OtherEngineering Knowledge Base — Ayush BasakExplore Ayush Basak's published engineering essays, snippets, notes, papers, books, product stories, and architecture resources in one place.
- OtherMovies - Ayush BasakFilms Ayush Basak returns to, and the ideas that make them memorable.
- Research & booksPapershelf - Ayush BasakResearch papers with practical engineering takeaways
- EssaysBuilding AI Products for AccessibilityProduct principles for AI-assisted reading experiences.
- EssaysThe Agent Was Interrupted. Should Its Work Disappear?Agent swarm concurrency explained through an interactive lab: wound-wait, page-level commits, prefix-safe updates, and the limits of preserving reasoning.
- EssaysAI Agents Need a Control Plane, Not a Larger PromptA production architecture for AI-agent identity, MCP authorization, bounded tools, policy enforcement, budgets, approvals, and auditable execution.
- EssaysAI Agent Memory Is Governed StateA production architecture for agent memory: provenance, consent, retention, retrieval boundaries, conflict resolution, evaluation, and deletion.
- EssaysAI Agent SSRF Prevention: Put URL Fetching Behind an Egress PolicyDesign safe URL-fetching tools for AI agents using constrained destinations, redirect handling, connection-time enforcement, and bounded responses.
- EssaysAI Evals Are Release EngineeringA CTO-level control plane for shipping AI systems with task-specific evals, regression gates, production feedback, safe rollout, and rollback evidence.
- EssaysAI-Generated Code Creates Review DebtGovern AI-assisted delivery by bounding change size, preserving authorship, testing behavior, and measuring review load.
- EssaysAI Inference Routing Is Capacity ControlA production design for routing AI inference by task, risk, latency, cost, capability, evaluation evidence, and deterministic fallback—not model fashion.
- EssaysEvolve APIs Without Flag DaysA production migration protocol for compatibility envelopes, expand-contract changes, Protobuf schemas, events, observability, and deletion evidence.
- EssaysArchitecture Decisions Need Expiry DatesA CTO-level operating model for architecture decisions: explicit context, measurable consequences, review triggers, ownership, and reversible migration paths.
- EssaysAutoscaling Cannot Recover an Expired DeadlineModel HPA as a delayed feedback loop: metric lag, startup time, dependency capacity, stabilization, and the admission controls needed before new Pods arrive.
- EssaysBackups Do Not Prove RecoverabilityA CTO-level recovery design for RPO, RTO, PostgreSQL PITR, dependency order, restore drills, and evidence that the business can survive data loss.
- EssaysBloom Filters Turn Memory into an Error BudgetSize and operate Bloom filters from allowed false positives, expected cardinality, and downstream cost.
- EssaysBM25 From First Principles: The Math, the Index, and Production RankingA rigorous guide to BM25 search ranking: derive IDF, term-frequency saturation, document-length normalization, calculate a score by hand, implement it, tune it, and place it inside a production retrieval stack.
- EssaysBuild vs Buy Is an Exit-Cost DecisionA practical CTO framework for evaluating software vendors through differentiation, operating cost, failure ownership, data portability, and credible exit paths.
- EssaysBuilding Microservices That Fail GracefullyPractical patterns for resilient service-to-service communication.
- EssaysCache Invalidation Is a Consistency ProtocolA production guide to cache-aside races, versioned keys, bounded staleness, invalidation delivery, stampede control, negative caching, and evidence of correctness.
- EssaysChange Data Capture Is a Recovery ContractA CTO-level guide to CDC snapshots, offsets, schema evolution, ordering, replay, lag, and proving downstream systems can recover without corrupting business state.
- EssaysScale the Blast Radius, Not Just the FleetA CTO-level guide to cell-based architecture: partition keys, routing, migration, observability, and deciding when fault isolation earns its operational cost.
- EssaysCloud Cost Is an Architecture MetricA CTO-level method for converting cloud bills into unit economics, ownership, cost attribution, capacity decisions, and engineering release gates.
- EssaysContinuous Batching Is a Scheduling PolicyOperate LLM continuous batching with explicit admission, fairness, prefill limits, cancellation, and tail-latency budgets.
- EssaysControl Planes Must Fail QuietlyA CTO-level architecture for separating control and data planes, bounding reconciliation, surviving stale configuration, and preventing management failures from becoming customer outages.
- EssaysCopy-on-Write Moves Cost to the First MutationUse copy-on-write with an explicit model for page faults, write amplification, memory pressure, and snapshot lifetime.
- EssaysCursor Pagination Is a Consistency ContractDesign cursor pagination around stable ordering, snapshot choices, opaque tokens, deletion behavior, authorization scope, and property-based tests.
- EssaysData Retention Is a System Design ProblemA production architecture for retention policy, deletion guarantees, PostgreSQL partitioning, backups, derived data, legal holds, and verifiable erasure.
- EssaysDatabase Credential Rotation: How to Replace Secrets Without Breaking Connection PoolsA rollout protocol for rotating database credentials across cached secrets, connection pools, workers, rollback windows, and emergency revocation.
- EssaysYour Timeout Budget Is an Architecture DecisionA CTO-level method for deadline propagation, retry budgets, jitter, and preventing one slow dependency from amplifying into a fleet-wide outage.
- EssaysDNS Failover Is a Bounded-Staleness ProtocolHow recursive caches, TTL, negative caching, resolver behavior, health checks, and connection reuse determine the real recovery time of DNS-based failover.
- EssaysDurable AI Agents Need Workflow Semantics, Not Chat LoopsA production architecture for replayable agent state, idempotent tools, human approval, versioning, budgets, and recovery across long-running AI work.
- EssaysDurable Workflows Do Not Remove the Need for IdempotencyHow replay-based workflow engines recover orchestration, where activity ambiguity remains, and how to design deterministic workflows with idempotent effects.
- EssaysEmbedding Upgrades Are Data MigrationsRoll out a new embedding model with versioned vectors, dual indexes, measured retrieval quality, and a reversible cutover.
- EssaysAn Error Budget Should Change the RoadmapHow technical leaders turn SLOs and error budgets into an explicit policy for releases, reliability investment, incidents, and product tradeoffs.
- EssaysExternal Consistency Explained: Spanner, TrueTime, and Commit WaitWhat Spanner's TrueTime and commit wait teach architects about real-time ordering, multi-region writes, locality, and honest consistency requirements.
- EssaysFeature Flags Are Production StateA CTO-level operating model for typed evaluation, safe defaults, targeting privacy, rollout evidence, flag debt, kill switches, and control-plane failure.
- EssaysYour Lock Expired. Your Worker Did Not.Understand stale-owner writes, monotonically increasing fencing tokens, atomic storage checks, and why leases alone cannot protect an external side effect.
- EssaysFiltered Vector Search Is a Recall BudgetWhy HNSW and IVFFlat filters can return too few results, how iterative scans help, and how to measure recall per tenant instead of trusting latency alone.
- EssaysgRPC’s HTTP/2 Transport Is Not the Reliability ModelSeparate HTTP/2 multiplexing and flow control from deadlines, retries, idempotency, and overload policy in gRPC systems.
- EssaysHeartbeats Measure Silence, Not FailureDesign failure detection around suspicion, consequence, and recovery—not a magic heartbeat timeout.
- EssaysHello WorldMy first blog post.
- EssaysHTTP Early Data Is a Replay BoundaryA production guide to QUIC and TLS 0-RTT replay risk, idempotent operations, 425 Too Early, anti-replay limits, and safe rollout policy.
- EssaysIncident Command Is a Distributed SystemHow CTOs can design incident response around explicit authority, shared state, bounded coordination, customer communication, and evidence-driven recovery.
- OtherEngineering Blog - Ayush BasakPractical essays on distributed systems, production AI, infrastructure, and software architecture.
- EssaysJWT Verification Is a Key-Distribution SystemHow issuer binding, algorithm allowlists, JWKS rotation, cache policy, unknown key IDs, and outage behavior determine whether JWT verification is secure and available.
- EssaysKafka Exactly-Once Stops at the Side-Effect BoundaryWhere Kafka transactions provide atomicity, where they do not, and how to design external effects without magical guarantees.
- EssaysAdding Kafka Partitions Changes the Ordering ContractScale Kafka partitions without accidentally changing key affinity, consumer concurrency, and the order your product relies on.
- EssaysKafka Poison Messages: Dead-Letter Queues Without Silent Data LossDesign Kafka consumer recovery around offset ownership, durable quarantine, per-key ordering, and safe replay instead of endless retries.
- EssaysA Kafka Rebalance Is a Coordination Protocol, Not a Consumer RestartHow Kafka consumer ownership, eager and cooperative rebalancing, offset commits, static membership, and generation fencing shape correctness and availability.
- EssaysKafka Tombstones: Why a Compacted Topic Can Leave Stale Consumer StateUnderstand Kafka tombstone retention, stale materialized views, rebuild boundaries, and the recovery policy needed after a consumer misses a deletion.
- EssaysKubernetes Availability Is Placement Plus Disruption PolicyWhy replicas alone do not create availability, and how topology spread, disruption budgets, probes, and capacity must form one failure-domain policy.
- EssaysKYAML in Practice: Explicit Kubernetes Manifests Without a MigrationHow KYAML changes manifest formatting, how to generate it, and where the tradeoff is useful.
- EssaysKubernetes Probes Are Failure Policy, Not Health EndpointsDesigning startup, readiness, and liveness probes around distinct recovery actions without turning dependency failures into restart storms.
- EssaysKubernetes Requests Are an Economic ModelA CTO-level method for setting Kubernetes requests, limits, QoS, autoscaling, and capacity policy from workload evidence instead of copied YAML.
- EssaysKubernetes Termination Is a Distributed ProtocolWhy SIGTERM, EndpointSlices, readiness, connection draining, and grace periods must be designed as one shutdown contract.
- EssaysLLM Serving Is KV-Cache Capacity PlanningA practical model for PagedAttention, continuous batching, admission control, and the latency-throughput trade-offs of production LLM inference.
- EssaysA Modern PostgreSQL JDBC Driver Built for Virtual Threads and Native ProtocolsExplore the architecture of pg-java, a PostgreSQL-first driver leveraging Java 21 virtual threads, ReentrantLock unpinning, and decoupled JDBC layering.
- EssaysTenant Isolation Is a Data Model, Not a WHERE ClauseA CTO-level guide to pooled and siloed SaaS tenancy, PostgreSQL row security, identity propagation, noisy-neighbor controls, and proving isolation in production.
- EssaysStrongly Consistent Object Storage Still Needs Concurrency ControlWhy S3 strong consistency does not prevent lost updates, and how conditional writes, immutable keys, checksums, versioning, and metadata transactions create safe object workflows.
- EssaysThinking Through Offline-First PaymentsSecurity and distributed-systems lessons from moving value without a live server.
- EssaysOpenTelemetry Baggage Is Untrusted InputDesign trace-context propagation without leaking secrets, trusting forged metadata, or turning observability labels into an authorization channel.
- EssaysThe OpenTelemetry Collector Is a Loss BudgetHow queues, retries, memory limits, persistent storage, and stateful processors determine which production evidence survives an outage.
- EssaysObservability Is a Data Contract, Not a Dashboard PurchaseHow engineering leaders can use OpenTelemetry semantics, cardinality budgets, context propagation, and SLO questions to build portable operational evidence.
- EssaysTranspiling Multi-Language DB Functions to PL/pgSQL with plxLearn how the plx extension transpiles familiar programming languages like Python, JS, and Go into native PL/pgSQL for zero-overhead execution inside PostgreSQL.
- EssaysA PodDisruptionBudget Is a Maintenance ContractUse Kubernetes disruption budgets with topology, rollout policy, capacity headroom, and drain tests instead of treating them as availability insurance.
- EssaysPostgreSQL Minor Updates: CVE-2026-6464 and Index MaintenanceAn engineering analysis of PostgreSQL 18.6, CVE-2026-6464, skipped 18.5, and post-upgrade REINDEX tasks for GIN, btree_gist, and ltree extensions.
- EssaysPostgreSQL Checkpoints Are Latency Events, Not Maintenance EventsHow checkpoint pacing, WAL pressure, full-page writes, and storage headroom shape PostgreSQL tail latency.
- EssaysPostgreSQL Connections Are a Capacity BudgetA production design for connection admission, pool sizing, PgBouncer modes, reserved capacity, queueing, and preventing autoscaling from overwhelming PostgreSQL.
- EssaysPostgreSQL Deadlocks: Lock Ordering, Transaction Retries, and Safe RecoveryReproduce a PostgreSQL deadlock, establish a lock-ordering contract, and design transaction retries that preserve business correctness.
- EssaysPrevent Double Booking with PostgreSQL Exclusion ConstraintsModel booking conflicts with PostgreSQL ranges and exclusion constraints, then handle cancellation, retries, tenant boundaries, and payment failure explicitly.
- EssaysPostgreSQL HOT Updates Are a Physical Design ContractIncrease PostgreSQL HOT updates by aligning indexes, fillfactor, row width, and update patterns with the heap page layout.
- EssaysEvery PostgreSQL Index Spends a Write-Amplification BudgetHow secondary indexes affect updates, HOT eligibility, page splits, vacuum work, and the operational cost of read optimization.
- EssaysPostgreSQL Logical Replication Failover: The Slot Is Part of Your Recovery PlanHow to make PostgreSQL logical subscribers survive publisher failover, verify synchronized slots, and design an honest recovery objective.
- EssaysWhy a Prepared PostgreSQL Query Gets Slower After Warm-UpDiagnose generic-plan regressions under tenant skew, compare real execution plans, and choose a scoped fix without disabling prepared statements everywhere.
- EssaysPostgreSQL Replication Slots Are Retention LeasesHow restart_lsn, catalog_xmin, retained WAL, slot invalidation, and consumer ownership turn replication slots into explicit capacity commitments.
- EssaysTenant Isolation Should Not Depend on Every WHERE ClauseA production guide to PostgreSQL row-level security: policy design, connection context, owner bypass, testing, performance, and operational safeguards.
- EssaysPostgreSQL Synchronous Replication Is a Commit ContractHow synchronous_commit, quorum standbys, remote_apply, failure domains, and commit latency define the durability you actually sell to customers.
- EssaysPostgreSQL Vacuum Is Concurrency Control, Not HousekeepingA mechanical guide to MVCC dead tuples, visibility horizons, autovacuum thresholds, transaction-ID freezing, wraparound, and the sessions that prevent cleanup.
- EssaysPostgreSQL work_mem: Budget for Concurrent Queries, Not One Fast SortTune PostgreSQL work_mem using query plans, concurrent operators, parallel workers, and spill costs without turning a faster report into a memory incident.
- EssaysPostgreSQL Zero-Downtime Schema Migrations: A Production GuideA production playbook for expand-backfill-contract migrations, PostgreSQL lock control, concurrent indexes, and safe constraint validation.
- EssaysProduct Quantization Is a Recall–Memory ContractReason about IVFPQ through memory, candidate coverage, quantization error, reranking, and measured retrieval recall.
- EssaysProduction AI Needs Release Gates, Not a Trust ScoreA practical operating model for AI risk: use-case boundaries, eval gates, authority limits, observability, degradation, and accountable production release.
- EssaysPrompt Caching Is a Context-Layout ProblemHow stable prefixes, tenant boundaries, invalidation, observability, and privacy turn prompt caching into AI infrastructure design.
- EssaysQueues Hide Overload Until Recovery Becomes ImpossibleHow CTOs should reason about bounded queues, admission control, backpressure, load shedding, and recovery time before asynchronous architecture becomes an outage amplifier.
- EssaysQUIC Migration Is Not Session ContinuityUnderstand what QUIC connection migration preserves—and what application sessions, authorization, and idempotency must still guarantee.
- EssaysA Raft Write Is Not Committed Just Because Most Replicas Have ItA mechanical deep dive into Raft terms, elections, log replication, the current-term commit rule, linearizable reads, persistence ordering, and ambiguous client outcomes.
- EssaysRAG Access Control: What Happens After Document Permission Is Revoked?Design permission-aware RAG around query-time authorization, chunk provenance, answer caches, revocation windows, and adversarial tests.
- EssaysRAG Quality Starts with Retrieval EvidenceDebug retrieval-augmented generation by separating corpus, retrieval, context assembly, generation, and citation failures.
- EssaysRate Limiting Is Admission ControlHow identity, fairness, concurrency, Retry-After, distributed counters, and overload policy turn rate limits into a product reliability boundary.
- EssaysA Read Replica Needs a Freshness ContractDesign PostgreSQL replica routing around observable staleness, read-your-writes guarantees, recovery conflicts, and explicit fallback policy.
- EssaysRefresh-Token Rotation Is a Replay DetectorImplement OAuth refresh-token families with atomic rotation, reuse detection, bounded grace, and grant-level revocation.
- EssaysReliable Scheduled Jobs: Idempotency, Missed Runs, and Time ZonesDesign scheduled jobs around durable occurrence identities, explicit catch-up rules, time-zone semantics, and recovery from partial business effects.
- EssaysWhy Rust Fits Infrastructure WorkWhat Rust changes when reliability and resource use both matter.
- EssaysS3 Multipart Uploads Need Garbage CollectionOperate multipart uploads with idempotent completion, bounded retries, checksums, lifecycle cleanup, and explicit ownership.
- EssaysS3 Presigned Uploads: Ownership, Overwrites, and Safe FinalizationDesign direct-to-S3 uploads with server-owned object keys, constrained capabilities, quarantine, object verification, and idempotent finalization.
- EssaysSaga Compensation Is Not RollbackDesigning distributed workflows when completed side effects cannot be erased: semantic compensation, idempotency, orchestration, and manual resolution.
- EssaysKiro Flock Explained: Multi-Agent Coordination with S3How kiro-flock coordinates Kiro CLI agents through shared S3 logs, and how to choose between peer coordination and a supervisor.
- EssaysSerializable Isolation Is a Retry Protocol, Not a CheckboxHow PostgreSQL Serializable Snapshot Isolation prevents write skew, why serialization failures are correct behavior, and how to build bounded transaction retries.
- EssaysDesign Service Identity Before Buying a Service MeshA production design for workload identity, SPIFFE trust domains, short-lived credentials, authorization, rotation, and migration away from shared service secrets.
- EssaysSharded Postgres: Query Locality Is the Architecture ContractHow to evaluate sharded PostgreSQL: tenant locality, distributed query costs, connection budgets, snapshot guarantees, and failure policies.
- EssaysA Shared Cache Key Is a Data-Isolation BoundaryAudit authenticated HTTP caching through representation keys, private/no-store semantics, revocation windows, and two-user cache-hit tests.
- EssaysFrom Repository to Real ProductA practical checklist for turning a full-stack build into a product people can rely on.
- EssaysValid JSON Is Not Permission to ExecuteSeparate AI output shape from factual evidence, authorization, freshness, and transactional execution using a concrete proposal-to-command boundary.
- EssaysSynchDB 1.4: Oracle CDB Support and Secured FDW SnapshotsSynchDB 1.4 introduces Oracle Container Database support across CDC, FDW, and OLR paths, plus TLS and Oracle Wallet encryption for initial snapshot data transfers.
- EssaysTail Sampling Is a Memory Budget Disguised as an Observability FeatureHow tail-based trace sampling buffers incomplete traces, routes spans consistently, makes late decisions, and fails under cardinality, bursts, and collector loss.
- EssaysTechnical Decision Models CompoundBuild lasting engineering leverage by recording constraints, invariants, evidence, and reversibility—not memorizing tools.
- EssaysThe Cost of ComplexityWhy simple systems fail less often than complex ones, and how to think about architectural decisions.
- EssaysThe Transactional Outbox Is Not the Delivery GuaranteeA CTO-level design for atomic event creation, idempotent relays and consumers, ordering, replay, and end-to-end delivery evidence.
- EssaysUSB Explained: Enumeration, Endpoints, Transfers, and What BreaksUnderstand how USB devices become usable: host control, descriptors, endpoints, transfer types, speed limits, and a practical debugging checklist.
- EssaysVerify What You DeployA CTO-level software supply-chain design for immutable artifacts, SLSA provenance, Sigstore verification, admission policy, builder trust, and incident response.
- EssaysWAL, S3, and Postgres Branching: What AI Agents Can Safely UndoHow Lakebase-style Postgres separates WAL durability from page storage, and what branching means for agent isolation, cold reads, and recovery.
- EssaysA Webhook Endpoint Is a Durable InboxDesign webhook ingestion around raw-body authentication, durable acceptance, idempotent effects, unordered delivery, replay defense, and reconciliation.
- OtherPrivacy PolicyHow ayushworks.xyz handles website analytics, browser preferences, email enquiries, embedded videos, and links to external AI services.
- OtherProjects - Ayush BasakSelected software projects by Ayush Basak
- OtherWebsite Security PolicyHow to privately report a vulnerability affecting ayushworks.xyz, what to include, and the boundaries for safe security reporting.
- OtherSecurity Engineering — Ayush BasakPractical guides to securing multi-tenant applications, bots, and RAG systems. Threat models, implementation boundaries, and tests that prove access is denied.
- OtherSecuring Multi-Tenant Systems: From Request Identity to Data DeletionA practical tenant-isolation guide covering authorization, PostgreSQL RLS, pooled connections, caches, queues, storage, resource limits, and offboarding.
- SnippetsSingle-Flight Scheduled Jobs with PostgreSQL Advisory LocksEnsure only one application replica runs a scheduled job by using a session-level PostgreSQL advisory lock.
- SnippetsBound AI Agent Execution by Tools, Tokens, Time, and SpendA production AI-agent control pattern with explicit step, token, tool-time, authorization, audit, and spend budgets.
- SnippetsBounded Retry in TypeScript — Exponential Backoff and JitterA production TypeScript retry pattern with exponential backoff, jitter, attempt limits, and a caller deadline.
- SnippetsPrevent Cache Stampedes with Stale-While-RevalidateServe bounded-stale data and coordinate one refresh to protect a database when a hot cache key expires.
- SnippetsPostgreSQL Checkpoint Pressure DiagnosticDistinguish WAL-triggered checkpoints from slow storage using pg_stat_checkpointer deltas.
- SnippetsCapacity-Protecting Circuit Breaker for TypeScript ServicesA production circuit-breaker boundary with distributed half-open admission, typed failures, deadlines, and explicit recovery policy.
- SnippetsIdempotent Durable Workflow ActivityProtect a retryable workflow activity with stable command identity and explicit terminal failure classification.
- SnippetsExpand-Contract Database Migration Without DowntimeA safe multi-deployment pattern for renaming or reshaping production database columns without a flag day.
- SnippetsDistributed Lease with Monotonic Fencing TokensPrevent stale workers from committing after lease expiry by requiring monotonic fencing tokens at every protected write.
- SnippetsGraceful Node.js HTTP Shutdown During DeploymentsDrain in-flight Node.js HTTP requests safely after SIGTERM while failing readiness and enforcing a shutdown deadline.
- SnippetsPostgreSQL Idempotent Command Handler PatternPrevent duplicate business effects when API clients retry after ambiguous network timeouts.
- SnippetsPostgreSQL Index Admission ReviewReview usage, size, update pressure, and HOT behavior before accepting another index.
- OtherEngineering Snippets — Production Backend Patterns by Ayush BasakCopy-paste production patterns for backend reliability, databases, distributed systems, infrastructure, security, observability, and AI agents.
- SnippetsKubernetes PodDisruptionBudget for Safe MaintenanceA minimal PodDisruptionBudget that preserves service capacity during voluntary Kubernetes maintenance.
- SnippetsKubernetes Termination Drain BudgetCoordinate readiness, preStop, drainage, and termination grace as one shutdown budget.
- SnippetsKafka External-Effect Idempotency KeyPreserve one business operation identity across Kafka redelivery and an external provider call.
- SnippetsStable PostgreSQL Keyset Pagination with a Compound CursorReplace slow and inconsistent OFFSET pagination with a deterministic PostgreSQL compound cursor.
- SnippetsLLM KV-Cache Admission BudgetReject or queue LLM requests before allocation when their reserved token demand cannot fit the configured service-class budget.
- SnippetsValidate LLM Output with Zod Before Side EffectsParse and validate structured LLM output with Zod before business rules, authorization, and deterministic side effects.
- SnippetsPolicy-Gated AI Model Router with Capacity ReservationRoute AI inference only among evaluated, policy-compliant models while reserving capacity, budget, and deadline before execution.
- SnippetsMonotonic Version Gate for Replicated StatePrevent delayed events or cache fills from overwriting newer replicated state by enforcing a monotonic version at the write boundary.
- SnippetsPostgreSQL Optimistic Concurrency Control with a Version ColumnPrevent lost updates by making a PostgreSQL write conditional on the version originally read.
- SnippetsClaim a PostgreSQL Outbox Batch with SKIP LOCKEDA PostgreSQL SKIP LOCKED pattern for parallel transactional-outbox relay workers.
- SnippetsAbortable Polling in TypeScript Without Overlapping RequestsA small TypeScript polling loop with cancellation, stable intervals, and no overlapping requests.
- SnippetsCalculate a Traffic-Weighted SLO Error Ratio in PromQLCompute a correct traffic-weighted HTTP error ratio in Prometheus without averaging percentages.
- SnippetsVersioned Prompt Prefix LayoutArrange stable, tenant-scoped, session, and volatile LLM context for safe cache reuse.
- SnippetsAtomic Redis Sliding-Window Rate Limiter with LuaA Redis Lua sliding-window rate limiter that makes admission and accounting one atomic operation.
- SnippetsStatically Stable Release Kill SwitchKeep a signed, versioned release-policy snapshot locally available so mitigation survives control-plane failure.
- SnippetsPropagate Request Deadlines with AbortSignal in TypeScriptBound downstream TypeScript work with AbortSignal so it cannot outlive the caller's latency budget.
- SnippetsPostgreSQL Retention with Partition Detach and Verified DropExpire high-volume PostgreSQL data through a retention-aligned partition lifecycle instead of disruptive row-by-row deletion.
- SnippetsPostgreSQL Serializable Transaction RetryRetry a complete PostgreSQL serializable transaction with bounded attempts, jitter, and explicit SQLSTATE classification.
- SnippetsSSRF-Safe URL Validation in TypeScriptValidate protocols, resolved addresses, redirects, and connection targets before fetching a user-supplied URL.
- SnippetsStructured Logging at a Backend Service BoundaryA compact structured logging pattern that records causal identity, tenant, outcome, and duration at service boundaries.
- SnippetsKubernetes Zone Spread and Disruption BudgetKeep replicas distributed across zones and bound voluntary disruption with a matching Kubernetes PDB.
- OtherSystems Architect — Backend, Distributed Systems and AI InfrastructureSystems architecture by Ayush Basak across backend platforms, distributed systems, databases, cloud infrastructure, APIs, and production AI.
- OtherTerms and ConditionsTerms for using Ayush Basak’s portfolio, engineering articles, code examples, and interactive tools on ayushworks.xyz.
- OtherVideos and Talks — Ayush BasakVideos, technical explanations, product discussions, and conference appearances by Ayush Basak.
- OtherCTO and Systems Architecture Work in Kolkata - Ayush BasakCTO, database engineering, and systems architecture work by Ayush Basak in Kolkata—covering technical direction, backend platforms, distributed systems, and production AI.
- OtherCTO Workbench V2 — Architecture Failure SimulatorConnect traffic, retries, caches, databases, queues, and workers to find where an architecture breaks first and turn assumptions into production invariants.
- OtherCTO Workbench — Ayush BasakInteractive engineering decision models for capacity, database connections, retries, queues, error budgets, cache economics, and the business cost of failure.