Engineering handbook
How I build and run software, written down. Twenty deep dives that show the way I work from schema to deployment, and a searchable collection of field notes behind them.
- deep dives
- 20deep dives
- field notes
- 281field notes
- areas of practice
- 14areas of practice
The signature twenty
The pieces that best show how I think: systems and ERP depth first, then delivery and leadership, then the craft underneath.
- 9 min readMulti-tenancy: AsyncLocalStorage context scoping and zero cross-tenant leakageHow to enforce tenant isolation at the database layer using Node.js AsyncLocalStorage. Why manual query filtering fails, and how to guarantee strict multi-tenant boundaries in NestJS and MongoDB.Multi-tenancyNestJSAsyncLocalStorageMongoDB
- 8 min read3-tier enterprise SaaS: Platform Admins, Reseller Consultancies, and Client PortalsArchitecting a multi-tier B2B ecosystem. How to support Platform Admins, Layer 2 white-label reseller consultancies, and Layer 3 employer clients with custom branding, dynamic entitlements, and audit isolation.SaaS ArchitectureNestJSMulti-TenancyWhite-Label
- 8 min readAutomated regulatory PDF generation at scale: 28 templates without memory leaksEngineering a high-volume PDF generator for site inspection audits. How to compile 28 regulatory compliance templates with embedded photo evidence and digital signatures while preventing Node/Java heap exhaustion.PDF EnginePerformanceRegulatory ComplianceMicroservices
- 7 min readWholesale margin and complex billing engines: real-time profit calculationsBuilding a high-precision wholesale telecom billing engine. Calculating multi-tier gross margins, fluctuating product tariffs, and real-time revenue analytics with MongoDB aggregation pipelines.Billing EngineMongoDBCalculationsCRM
- 8 min readResolving 600+ production bugs: a systematic playbook for stabilizing legacy codeHow to triage, profile, and permanently resolve high volumes of production bugs. Lessons from eliminating over 600 bugs on an enterprise UK site audit compliance platform.DebuggingSystem ReliabilityTechnical DebtRefactoring
- 7 min readFast-track engineering leadership: from trainee to tech lead in four monthsHow taking absolute ownership, fixing 600+ bugs, and designing scalable multi-tenant architecture led to rapid promotion from Software Engineering Trainee to Tech Lead in ~4 months.LeadershipCareer GrowthOwnershipSystem Architecture
- 9 min readEnterprise policy rule engines: biometric attendance, sandwich rules, and PMSDesigning complex workforce policy engines. Handling sandwich rule leave calculations, geofenced biometric punch-out reconciliation, automated Loss of Pay (LOP), and 3-tier PMS appraisals.Policy EngineHRMSBiometricsPMS
- 8 min readJWT cookie authentication: httpOnly tokens, silent refresh, and session revocationWhy storing JWTs in localStorage is an XSS vulnerability. How to implement secure httpOnly cookies, silent token rotation, CSRF protection, and Redis-backed session revocation.AuthenticationSecurityJWTCookies
- 8 min read5-level hierarchical RBAC: role-aware DTOs and dynamic NestJS guardsImplementing 5-level hierarchical role-based access control. How custom decorators, permission bitmasks, and response DTO filtering prevent unauthorized actions and data leakage.RBACAuthorizationNestJSSecurity
- 8 min readSwappable cloud storage: abstracting AWS S3 and Azure Blob with SAS tokensDesigning a unified cloud storage driver. How to seamlessly switch between AWS S3 signed URLs and Azure Blob SAS tokens without changing application business logic.Cloud StorageAWS S3Azure BlobArchitecture
- 8 min readWebhook event delivery pipelines: HMAC verification, idempotency, and retriesEngineering a mission-critical webhook dispatch system. Delivering signed lifecycle events with exponential backoff, dead-letter queues, and idempotency guarantees in NestJS and Redis.WebhooksEvent-DrivenRedisBullMQ
- 7 min readProduction cloud deployments: automated GitHub Actions CI/CD on AWS EC2 & AzureDeploying high-availability Node.js and NestJS microservices onto AWS EC2 and Azure VMs. Setting up automated GitHub Actions pipelines, Nginx reverse proxies, PM2 clustering, and SSL rotation.CI/CDGitHub ActionsAWS EC2Azure Cloud
- 7 min readNestJS vertical slices: structuring enterprise modules for independence and testabilityWhy horizontal layering (all controllers, all services in root folders) breaks down. How vertical feature slices improve cohesion, velocity, and maintainability in large codebases.NestJSClean ArchitectureModular DesignTypeScript
- 7 min readAPI design rules: predictable endpoints, pagination, and error contractsDesigning clean RESTful contracts. Consistent resource naming, RFC 7807 problem details, cursor-based pagination, and backward-compatible schema versioning.API DesignRESTPaginationError Handling
- 8 min readProduction security checklist: OWASP Top 10 defenses for multi-tenant APIsHardening public REST APIs against common attack vectors. Implementing rate limiting, strict CORS, input sanitization, NoSQL injection defenses, and security headers.SecurityOWASPRate LimitingCORS
- 7 min readGDPR and privacy by default: tenant data isolation, audit retention, and SAR exportsBuilding enterprise compliance into the core architecture. Handling Subject Access Requests (SAR), encrypted PII storage, right-to-erasure workflows, and immutable audit logs.GDPRComplianceSecurityAudit Logs
- 7 min readLightweight state and real-time dashboards: Zustand and TanStack QueryReplacing heavyweight Redux boilerplate with Zustand and TanStack Query. Managing optimistic updates, client-side caching, and responsive data visualization for enterprise CRMs.Frontend ArchitectureReactZustandTanStack Query
- 8 min readNext.js App Router in production: partial prefetching, instant shells, and streamingLeveraging Next.js 16 Partial Prefetching (PPR), Cache Components, and Suspense boundaries to achieve sub-50ms perceived navigation across complex enterprise pages.Next.jsReact 19App RouterPerformance
- 6 min readDocs-first delivery: why the schema and the contract come before the codeWriting architecture decision records (ADRs), interface contracts, and typed schemas before implementation. How documentation upfront accelerates velocity and prevents architectural rework.DocumentationADRArchitectureEngineering Practices
- 7 min readAI-assisted engineering: how I use autonomous agents and MCP in daily productionIntegrating Model Context Protocol (MCP), autonomous coding subagents, and strict verification loops into modern software delivery without hallucination or regressions.AI EngineeringMCPAutomationDeveloper Tooling
Field notes
Short, specific rules and lessons across 14 areas. Open one for the detail, or follow its link to the full write-up.
281 of 281 notes
ArchitectureDesign the data before the endpoints
Endpoints are cheap to change. A wrong schema in production is not. Sketch tables, relations and the tenancy model first.
ArchitectureArchitecture first, then code
No implementation before the design is reviewed. A day of design costs less than a week of rework.
ArchitectureWrite the module breakdown from the business requirements
A module map derived from real requirements keeps scope honest and gives every engineer the same picture.
ArchitecturePrefer vertical slices to horizontal layers
Organise by feature so one change touches one folder, instead of scattering a feature across controllers, services and models.
ArchitectureRecord every non-obvious decision
A short decision record states what was chosen, why, and what was rejected. It saves the next engineer from re-arguing it.
ArchitectureMake the boundary the contract
Between services, and between portal and ERP, define exactly what crosses and who owns it. Most integration pain is an unclear boundary.
ArchitectureStart with a modular monolith
Split into microservices only where billing, sync or scale earns it. Premature services multiply deployment and debugging cost.
ArchitectureSplit a service when it has a different failure or scaling profile
Usage-based billing and bulk sync behave differently from request/response APIs. That is a reason to separate them, not fashion.
ArchitecturePut an adapter in front of every third-party system
Your code talks to your interface. Swapping, mocking or retrying a vendor then touches one file.
ArchitecturePrefer boring technology on the critical path
Use well-understood tools for auth, payments and data. Spend novelty budget where it differentiates the product.
ArchitectureKnow what the system of record is
For every entity, name the one system that owns the truth. Everything else is a cache and should behave like one.
ArchitectureDesign for the failure of every dependency
Ask what happens when the ERP, the payment provider or the mail service is down. A queue and a status field beat an error page.
ArchitectureMake state transitions explicit
Orders, proposals and syncs move through named states. Encode allowed transitions so impossible states cannot exist.
ArchitectureKeep read models separate when reads dominate
Dashboards and lists can use shaped queries or cached projections without bending the write model.
ArchitecturePrefer idempotent operations
If doing it twice is safe, retries, replays and duplicate webhooks stop being incidents.
ArchitectureVersion anything a client depends on
API paths, webhook payloads, AL extension APIs. A breaking change gets a new version, and the old one keeps its contract.
ArchitecturePut cross-cutting concerns in the framework
Auth, validation, logging, error shaping and audit belong in guards, pipes, filters and interceptors, not in every handler.
ArchitectureDiagram the data flow, not the boxes
A sequence of who calls whom and what is stored tells you more than a layered picture ever will.
Backend and NestJSUse DTO classes for every payload
Each incoming body, query and param has a typed class with validation decorators. Nothing reaches a service unvalidated.
Backend and NestJSTurn on whitelisting in the validation pipe
Strip unknown properties, or reject them. It stops a client from smuggling a role or tenant id into a create call.
Backend and NestJSReturn response DTOs, not entities
Never serialise a database model directly. A response class decides exactly which fields can leave the system.
Backend and NestJSApply the auth guard globally
Protect by default and mark exceptions with a public decorator. Forgetting a guard should be impossible.
Backend and NestJSWrap the ORM in a repository
Services call repositories. Tests stub one small class and an ORM upgrade touches one layer.
Backend and NestJSLet a global exception filter shape every error
One place formats errors, hides stack traces and attaches an error code. Controllers throw and forget.
Backend and NestJSUse an interceptor for the response envelope
Wrapping success responses in one interceptor keeps every endpoint's shape identical.
Backend and NestJSLog writes through an audit interceptor
Capturing who changed what, automatically, gives support and compliance a trail without per-handler code.
Backend and NestJSKeep controllers thin
A controller parses input, calls a service and returns. If it has an if-statement about business rules, it is in the wrong place.
Backend and NestJSInject configuration, do not read process.env everywhere
A typed config service validated at startup fails fast on a missing variable instead of failing mid-request.
Backend and NestJSFail fast on bad environment
Validate required variables at boot. A crash on deploy is better than a half-working service.
Backend and NestJSPrefer constructor injection and small modules
Each module exports only what others need. Circular dependencies are a design smell, not a Nest quirk.
Backend and NestJSUse transactions for multi-step writes
Create-plus-children-plus-balances happen in one transaction. Test that a failure leaves nothing behind.
Backend and NestJSInside a transaction callback, use only the transaction client
Reaching for the outer client opens a second connection and can deadlock.
Backend and NestJSPaginate every list on the server
Default 20, maximum 100. Never return an unbounded collection.
Backend and NestJSWhitelist sortable and filterable fields
Query-string filters map onto a fixed list of columns, so a client cannot sort by anything it likes.
Backend and NestJSUse soft delete for personal data
Mark deleted, filter in one place, and purge for real after the retention period.
Backend and NestJSKeep long work off the request path
Queue, schedule or run it after responding. Users should not wait for an LLM call or a bulk sync.
Backend and NestJSUse a scheduler for retention and cleanup
Expiring tokens, purging old records and flagging stale state are jobs with tests, not manual chores.
Backend and NestJSPrefer a structured logger to console output
Structured logs with levels and correlation ids can be searched. Console lines cannot.
Backend and NestJSStrip PII from log lines
No emails, names or tokens in logs. Log ids and let people look the rest up where access is controlled.
Backend and NestJSHealth endpoints should check real dependencies
A health route that only returns ok hides a broken database connection.
Backend and NestJSUse URI versioning for public APIs
/api/v1/... makes versions visible, cacheable and routable at the proxy.
Backend and NestJSKeep module docs next to the module
A short page per module on what it does and which behaviour is deliberate saves archaeology later.
API designResources are nouns, collections are plural
GET /invoices, not GET /getInvoices. Nest relations: /companies/:id/users.
API designUse HTTP methods for what they mean
GET reads, POST creates, PUT replaces, PATCH updates part, DELETE removes. GET, PUT and DELETE must be idempotent.
API designOne response envelope for every endpoint
A success flag, data, and meta for pagination. Errors use the same outer shape.
API designUse stable error code constants
Clients should branch on a code like VALIDATION_FAILED, not parse a message.
API design400 means invalid, 422 means not allowed by a rule
Separate malformed input from valid input that violates a business rule.
API designUse 409 for conflicts
Unique constraint violations and state conflicts deserve their own status, so clients can handle them.
API design401 versus 403 is not interchangeable
401 is no or bad credentials. 403 is a valid user who is not allowed.
API designReturn 404 for soft-deleted records
To the client a deleted thing does not exist. Do not leak that it once did.
API designRate limit with a Retry-After header
A 429 without a retry hint invites hammering. Tell clients when to come back.
API designCap page size
A client that can request limit=100000 can take your database down.
API designReturn the total in meta
UIs need it for page controls, and a second count request wastes a round trip.
API designMerge count and find where the database allows
One pass for rows and total cut list latency noticeably on a busy platform.
API designNever change a contract in place
Add a field, deprecate, then version. A breaking change creates v2.
API designMake writes safe to retry
Accept an idempotency key on operations that create money or documents.
API designDocument with examples, not just schemas
A real request and response teaches faster than a field table. Gate interactive docs off in production.
API designModel long operations as resources
Return 202 with a status resource instead of holding a connection for minutes.
Security and authKeep access tokens short-lived
Fifteen minutes limits the damage of a leak. Use a refresh token for session length.
Security and authRotate refresh tokens on every use
Issue a new pair and revoke the old one immediately. A stolen, replayed token then fails.
Security and authStore refresh tokens hashed
If the database leaks, hashed refresh tokens cannot be replayed.
Security and authPut only what you need in the token
User id, tenant id, role. Anything else can be fetched, and anything readable is visible.
Security and authReject tokens without a tenant claim
In multi-tenant systems the guard is the choke point. A token with no tenant must never pass.
Security and authHash passwords with bcrypt at 12 rounds or more
Use 14 for new services. Never store, log or email a plaintext password.
Security and authUse cryptographic randomness for reset tokens
crypto.randomBytes, a TTL of 24 hours or less, and single use.
Security and authMake verification tokens one-time
Invalidate on use. A replayable link is a standing back door.
Security and authRate limit login harder than anything else
Five attempts a minute is plenty. Reset and resend endpoints get stricter limits still.
Security and authOffer TOTP 2FA, and enforce it for internal users
Admin accounts without a second factor are the usual way in.
Security and authNever use a wildcard CORS origin in production
Use an allowlist from configuration. Credentials plus wildcard is not allowed anyway, and for good reason.
Security and authSet security headers by default
helmet gives sensible defaults in one line. Strip X-Powered-By.
Security and authValidate file uploads by content
Check magic bytes, not the extension. Enforce a size limit and store outside the web root.
Security and authServe downloads with expiring signed links
Private storage plus time-limited URLs beats a public bucket every time.
Security and authPrefix storage paths with the tenant from the token
Never trust a client-supplied path prefix.
Security and authNever fetch a user-supplied URL without an allowlist
That is how SSRF starts. Resolve and check the destination.
Security and authAudit dependencies before you merge
npm audit and automated dependency updates. Check licences and maintenance for new packages.
Security and authCommit lock files and pin major versions
Reproducible installs are a security property, not just a convenience.
Security and authKeep secrets out of git, always
A committed example file lists names only. Check git status before staging, so a stray env file is spotted.
Security and authRotate any secret that touched a chat or a ticket
Treat it as compromised. Rotation is cheap, an incident is not.
Security and authSeparate response classes per role
Hiding a field with a ternary is how it leaks. A role without the property cannot return it.
Security and authRecord security findings, do not silently fix them
A public signup that accepts a role field belongs in the security notes and in a ticket, with a visible fix.
Security and authUse a threat model per integration
Three questions: what can go wrong, who can abuse it, what do we do about it. Keep it to a page.
Security and authVerify webhook signatures on raw bodies
Re-serialised JSON will not match. Reject and log failures.
Security and authPrefer least privilege for service accounts
Give an integration app the permission set it needs and nothing more.
Security and authMask secrets in every output
Logs, error pages, support screenshots and chat transcripts all end up somewhere.
Data and databasesUse time-ordered UUIDs for primary keys
They are unguessable, sortable by creation, and safe to generate in the app. Keep legacy ids in a separate column during migrations.
Data and databasesMoney is a decimal, and the API returns a string
Never a floating-point number. Decimal(28,10) for amounts, a narrower type for rates.
Data and databasesAdd timestamps to every table
createdAt, updatedAt and, where it applies, deletedAt. Debugging without them is guessing.
Data and databasesIndex what you filter and sort on
Look at real query shapes. Compound indexes should lead with the most selective column, and with the tenant id on shared tables.
Data and databasesProfile before you cache
Most slow screens are one bad query or too many queries. Fix the query, then decide whether a cache is still needed.
Data and databasesCollapse five analytics queries into one
A single well-shaped query often beats a chatty dashboard, and keeps the numbers consistent with each other.
Data and databasesUse enums for statuses and roles
Free-text statuses drift. An enum is validated by the database and visible in the schema.
Data and databasesModel small fixed shapes as columns
A borrower name and email are columns. Embedding them as an object buys nothing in a relational store.
Data and databasesModel lists with identity as child tables
Give them an id and a position. Free-form blobs go in a JSON column.
Data and databasesNever drop an array of ids
Use join tables. They are lossless, indexable and enforce referential integrity.
Data and databasesDecide foreign key delete rules deliberately
Restrict for financial links, SetNull for audit pointers, Cascade for owned children. Then test the delete flows.
Data and databasesEnforce invariants in the database too
A service-level check can be bypassed. A unique index or a CHECK constraint cannot.
Data and databasesUse partial unique indexes for conditional uniqueness
Unique only where the record is active, for example. It is expressive and enforced.
Data and databasesA unique violation aborts a Postgres transaction
You cannot retry the next statement inside it. Check for existence first, or retry the whole transaction.
Data and databasesMake migrations small and reversible in intent
One change per migration, named for what it does. Never edit one that has shipped.
Data and databasesRun a schema drift check in CI
The schema file and the migration history must agree, or someone's laptop is the real source of truth.
Data and databasesTest on the real database engine
An embedded stand-in is not the real thing. Concurrency, collation and error codes differ, so verify on real PostgreSQL.
Data and databasesQualify the schema in raw SQL
Raw queries can ignore the client's schema setting. Be explicit.
Data and databasesLower-case emails on write and on lookup
Otherwise the same person registers twice.
Data and databasesRemember text sort order depends on collation
Postgres and Mongo sort differently. Surface it in the migration notes if users sort lists.
Data and databasesAggregation pipelines skip query hooks
In Mongo, start every pipeline with a manual tenant match. Hooks do not run for aggregate.
Data and databasesSumming strings gives zero in Mongo aggregations
Money stored as strings breaks totals silently. Migrating to decimals reveals logic that never worked.
Data and databasesFilter nullish values before building ObjectIds
new ObjectId(undefined) creates a random id and a phantom link.
Data and databasesUse TTL indexes only for purely time-based expiry
For conditional retention, an explicit job is visible and testable.
Data and databasesPrefer ILIKE and contains before reaching for full-text search
Add trigram indexes later if it is slow. Measure first.
Data and databasesSoft-delete with a retention plan
Mark, filter centrally, purge on schedule. Document the period per data type.
Data and databasesReconcile after any bulk move
Counts, orphan foreign keys and exact decimal sums, checked directly on the target and not just in the script's report.
Multi-tenancyChoose the tenancy model before the first table
Shared tables, schema per tenant or database per tenant. It shapes migrations, backups and performance.
Multi-tenancyEnforce isolation in one place
A plugin, a guard or a row-level policy, never a filter each developer must remember.
Multi-tenancyCarry the tenant in the signed token
The server decides the tenant from the claim, never from a request field.
Multi-tenancyLead compound indexes with the tenant id
Scoped queries use them, and uniqueness becomes per tenant.
Multi-tenancyMake background jobs set the tenant explicitly
Outside a request there is no current tenant. A job without one should fail loudly.
Multi-tenancyTest with a second tenant
Create data for tenant A, authenticate as tenant B, and assert nothing comes back.
Multi-tenancySchema per tenant needs idempotent migrations
A failed run must be safe to run again. ON CONFLICT DO NOTHING is your friend.
Multi-tenancyUse a worker pool for per-tenant jobs
One connection per worker lets dozens of tenants migrate in parallel without starving the database.
Multi-tenancyReserve database per tenant for contractual needs
It has the highest operating cost. Use it when a contract demands separation, and no earlier.
Enterprise SaaS and BillingDraw the tenancy hierarchy first
Platform Admins govern global health; Resellers manage retained clients; Clients operate self-service portals.
Enterprise SaaS and BillingIsolate tenant state with AsyncLocalStorage
Carry tenant context in Node.js AsyncLocalStorage to prevent cross-tenant database leakage automatically.
Enterprise SaaS and BillingCompute money in integer minor units
Never use floating-point numbers for wholesale margins. Store pence/cents to eliminate compounding rounding errors.
Enterprise SaaS and BillingStream PDFs instead of buffering memory
When generating regulatory inspection certificates with photos, stream directly to response and cloud storage.
Enterprise SaaS and BillingAbstract cloud storage behind a common provider
Support both AWS S3 and Azure Blob SAS tokens through a swappable interface without changing business logic.
Enterprise SaaS and BillingSign outgoing webhook payloads with HMAC-SHA256
Allow subscriber endpoints to cryptographically verify payload authenticity using shared secret keys.
Enterprise SaaS and BillingEnforce sandwich rules across calendar boundaries
Weekend days sandwiched between active leaves must be automatically deducted according to corporate policy.
Enterprise SaaS and BillingSeparate client store from server cache
Manage API cache with TanStack Query and local UI interactions with lightweight Zustand stores.
Enterprise SaaS and BillingGate routes with 5-level hierarchical RBAC
Super Admin, Org Admin, HR Manager, Department Manager, and Employee inherit permissions through rank bitmasks.
Enterprise SaaS and BillingRotate refresh tokens on every single use
Detect token replay attacks in Redis and revoke the entire token family immediately upon breach detection.
Enterprise SaaS and BillingUse $facet aggregations for executive rollups
Compute deal totals, product category breakdowns, and gross profit distributions in a single indexed query.
Enterprise SaaS and BillingDownsample inspection photos before embedding
Mobile cameras capture 12MP photos. Downsample to 300 DPI WebP/JPEG to prevent PDF memory bloat.
Enterprise SaaS and BillingAdvance sync checkpoints only after database commit
If a worker crashes mid-batch, re-read from the last confirmed checkpoint rather than dropping events.
Enterprise SaaS and BillingMake upserts idempotent across all consumers
Replaying a webhook or document state transition multiple times must never duplicate invoice or ledger records.
Enterprise SaaS and BillingAnonymize PII instead of hard deleting audit logs
When users exercise Right to Erasure, hash identifiers with SHA-256 while preserving tax and financial transactions.
Enterprise SaaS and BillingRun automated CI/CD checks before cloud deploy
Enforce linting, type checks, and unit tests in GitHub Actions before deploying to AWS EC2 or Azure VMs.
Enterprise SaaS and BillingTriage legacy bugs by cluster patterns
70% of production issues cluster around uncontrolled async state mutations, missing null checks, or unclosed streams.
Enterprise SaaS and BillingWrite ADRs before implementing database schemas
Agreeing on entity relationships and boundary contracts upfront prevents expensive mid-flight architectural rework.
Enterprise SaaS and BillingEstablish automated health checks for zero-downtime reloads
PM2 clusters must verify the `/health` endpoint before terminating previous worker processes.
Enterprise SaaS and BillingScope audit logs to the tenant and actor
Record who modified an employee salary or approved a proposal with immutable timestamp and IP tracking.
Enterprise SaaS and BillingEnforce dynamic entitlement guards per subscription tier
Check whether a client organization subscribes to HR Advisory, Software, or Hybrid before granting feature execution.
Enterprise SaaS and BillingDeliver instant shells with Next.js Suspense
Wrap URL params inside Suspense boundaries to allow instant client prefetching across dynamic routes.
Enterprise SaaS and BillingCalibrate appraisals across normalized KPI bands
Self-appraisals and manager reviews must feed into HR executive normalization before salary revisions trigger.
Enterprise SaaS and BillingBuild with AI agents anchored to verified context
Constrain autonomous agents with architecture registers, strict type checks, and automated regression suites.
Integrations and paymentsVerify the signature of every webhook
HMAC over the raw body. Reject and log failures, never process them silently.
Integrations and paymentsUse the provider's event id as an idempotency key
Store processed ids. A repeated delivery then does nothing.
Integrations and paymentsSend idempotency keys when you create things
A retried create cannot charge or book twice.
Integrations and paymentsStore provider ids, never card or bank numbers
Customer, mandate and payment ids are enough to operate.
Integrations and paymentsGate business actions on the real state
A proposal waits for an active mandate. Enforce it on the server.
Integrations and paymentsReconcile with the provider regularly
A job compares your records with theirs and reports differences before finance does.
Integrations and paymentsReproduce an integration failure with a direct request
A 403 might be an account setting. A one-minute request proves it before you change code.
Integrations and paymentsPrefer the provider's current API flow
Legacy redirect flows tend to lose features and webhooks over time. Migrate before you are forced to.
Integrations and paymentsHandle every webhook type you subscribe to
A handler that is never triggered, or an event with no handler, is a silent gap.
Integrations and paymentsBack off and retry with jitter
Retries in lockstep become a second outage.
Integrations and paymentsTime-box every outbound call
A missing timeout is a latent outage. Set connection and read timeouts.
Integrations and paymentsLog the request id from every provider
Support conversations with a vendor need it.
Integrations and paymentsKeep integration credentials per environment
Test keys in test, live keys only in production, and never in the repository.
Integrations and paymentsTest with the provider's sandbox and published test data
Never use real customers or real money to check a flow.
Integrations and paymentsWrap OCR and AI vendors behind the same adapter style
Switching Google Vision for another engine should not touch the business logic.
Integrations and paymentsPlan for the vendor changing their API
Pin versions where you can, subscribe to change notices, and keep contract tests.
Frontend and UIServer state belongs in a query cache
TanStack Query for fetching, caching and syncing. No data fetching inside effects.
Frontend and UIWrap every query in a typed custom hook
Hooks give you one place for keys, types and invalidation.
Frontend and UICentralise query keys
Predictable keys make invalidation after a mutation boring, which is the goal.
Frontend and UIKeep client state tiny
If it came from the server, it is cached server state. A small store holds only the user, toggles and wizard steps.
Frontend and UIPrefer Zustand for new client state
A minimal API surface beats a large boilerplate for small stores.
Frontend and UIOwn your components
Build on accessible primitives with the code in the repository. No library upgrade to fear and no theming fight.
Frontend and UIAvoid heavy component suites in new projects
They are hard to theme and hard to unlearn. Add one only with a reason.
Frontend and UIUse React Hook Form for anything with more than three fields
Uncontrolled inputs and schema validation keep large forms fast.
Frontend and UIPaginate, search and sort on the server
A table that can grow must not load everything into the browser.
Frontend and UILoad dashboards per section
Each tab fetches what it shows, with its own date filter. One slow query must not block the page.
Frontend and UICollapse chatty screens
Merge calls, then cache. One dashboard dropped from seven calls to two to four.
Frontend and UIDesign loading, empty and error states
An empty screen is an invitation to act. An error says what happened and how to fix it.
Frontend and UIBuild role-aware screens from the session
Hiding a button is convenience. The API is the real gate.
Frontend and UIDefine design tokens as CSS custom properties
Colours, spacing and radii as variables. A missing token should fail loudly, not render an invisible control.
Frontend and UISupport dark mode from day one
Tokens that swap under a theme attribute are cheap early and painful late.
Frontend and UIRespect reduced motion
Disable non-essential animation under the user's preference. Motion should answer an action, not decorate a page.
Frontend and UIMake every control keyboard reachable
Visible focus, logical order and labels. Accessibility is part of the definition of done.
Frontend and UIDesign for every screen from a phone to an ultra-wide monitor
Fluid gutters, content caps and root-size scaling, tested at the extremes.
Frontend and UIShip static where you can
Public pages prerender and load fast, even on poor networks.
Frontend and UIUse route groups to separate public and authenticated areas
The folder structure then mirrors the product.
Frontend and UILet middleware save a round trip, not enforce security
It can redirect an expired session, but the API is the boundary.
Frontend and UIPush client components down the tree
Keep the interactive leaf small. The rest can render on the server.
Frontend and UIRead the docs for the installed framework version
Conventions change between majors. The repository's version is the truth, not memory.
Frontend and UIDelete dead hooks and helpers
A permissions hook nobody wires in returns false for everyone. Gate on what the app actually uses.
DevOps and cloudPick the cloud region once and record it
For residency-bound work the region is a contract term. Everything touching data stays inside it.
DevOps and cloudDeploy on merge
A pipeline that deploys every merge keeps releases small, boring and reversible.
DevOps and cloudBlock merges on failed checks
Lint, types, tests and build are required. A red check is not a suggestion.
DevOps and cloudRun the build as its own step
The log then shows the real error. Do not redirect it into a file and guess.
DevOps and cloudPin tool versions in pipelines
A floating CLI or Node version is a surprise waiting for a Friday.
DevOps and cloudCache dependencies in CI
Faster feedback keeps people running the checks.
DevOps and cloudCreate preview deployments for pull requests
Reviewers click the change instead of imagining it.
DevOps and cloudUse a branch strategy that fits the team
Main is production, develop is integration, features are short-lived. Never force-push main.
DevOps and cloudRun migrations in the pipeline
A deploy step runs them with the production command. Nobody runs them from a laptop.
DevOps and cloudKeep secrets in the platform's store
Environment secrets or a vault, never the repository. Provide an example file with names only.
DevOps and cloudSeparate configuration per environment
Including CORS allowlists, callback URLs and feature flags.
DevOps and cloudTerminate TLS at the platform and renew automatically
Expired certificates are an outage you scheduled yourself.
DevOps and cloudUse containers for APIs with health checks
A health check that touches the database tells the platform when to restart.
DevOps and cloudUse a VM and process manager for steady sync workers
A long-running worker behind a reverse proxy can beat a function with timeouts and cold starts.
DevOps and cloudPut Nginx in front of Node when you run it yourself
TLS, compression, caching and request limits belong at the edge.
DevOps and cloudRestart with PM2, and keep logs rotated
A process manager gives restarts, clustering and logs. Rotate them so disks do not fill.
DevOps and cloudKeep object storage private
Use time-limited signed links. A public bucket is an incident waiting to be indexed.
DevOps and cloudPrefix storage by tenant
Paths come from the token, not the request.
DevOps and cloudMonitor before you launch
Logs, alerts and a status check should exist before the first user does.
DevOps and cloudBack up, and rehearse the restore
A backup you have never restored is a hope.
DevOps and cloudWrite the runbook while you remember
How to deploy, roll back, rotate a secret and read the logs. The next person is probably you in three months.
DevOps and cloudUse infrastructure as code where it pays for itself
Terraform for the parts you would otherwise click through twice.
DevOps and cloudAvoid broad process kills
Kill by the port you started. Patterns like 'nest start' match other people's servers.
Testing and qualitySet coverage floors and enforce them
80 percent overall and 90 percent for authentication. A floor is a conversation starter, not a goal.
Testing and qualityTest on the real database
Happy path, validation, 404, 400, 409, soft delete, pagination, foreign keys and rollback.
Testing and qualityUse realistic fixtures for validation
Dozens of real postcodes, not two synthetic ones. Edge cases are where bugs live.
Testing and qualityTest every endpoint as every role
Assert status and response shape. A role matrix test is the cheapest access-control audit.
Testing and qualityTest cross-tenant isolation explicitly
A second tenant should see nothing, and not even learn the record exists.
Testing and qualityAssert that failures leave nothing behind
A transaction test checks rows and counters after a thrown error.
Testing and qualityRecord the failing baseline first
Then you can prove you reduced it, and nobody blames you for old failures.
Testing and qualityRewrite broken tests to the current contract
Never skip or loosen them to get green.
Testing and qualityReplace mock-heavy specs with integration tests
Cover the same scenarios against real behaviour, then add the gaps.
Testing and qualitySmoke-test in a real browser
A passing unit test does not prove a screen works. Click the flow a client will click first.
Testing and qualitySearch the whole codebase for other instances of a bug
The reported file is rarely the only place. Search unscoped first, then narrow.
Testing and qualityLook for duplicated constants in lib folders too
Hard-coded values hide in helpers as often as in components.
Testing and qualityTreat a green build as necessary, not sufficient
Ask whether something existing should have been reused, and whether a related workflow is now broken.
Testing and qualityRun broad checks before marking a ticket done
Eleven tickets marked done and several reopened taught me this the expensive way.
Testing and qualityRun lint and format only on files you changed
A repo-wide formatter creates a diff nobody can review.
Testing and qualityGate the whole set behind one verify command
Schema validation, drift check, audits, lint, types, tests, build. If it is green, it is shippable.
Delivery and leadershipAgree requirements in writing, with priorities
Numbered, prioritised items agreed before development. It removes most late surprises.
Delivery and leadershipGive every project the same docs vault
A standard structure means any engineer, client or agent knows where to look.
Delivery and leadershipUpdate the docs in the same commit as the code
Docs written later are fiction.
Delivery and leadershipKeep a traceability matrix
Requirement to ticket to page. It answers 'where is that feature' in a minute.
Delivery and leadershipTurn architectural rules into CI checks
A rule in a document drifts. A failing build does not.
Delivery and leadershipWrite a rich description on every ticket
Two to four sentences in the past tense: what was done, for whom, what was resolved, the outcome. Never a bare title.
Delivery and leadershipEstimate with ranges and name the assumptions
A single number is a promise you cannot keep.
Delivery and leadershipShow working software early
A preview deployment beats a status meeting.
Delivery and leadershipReport honestly
What is done, what is risky, what is not yet verified.
Delivery and leadershipReview for correctness, then security, then fit
Style belongs to the linter.
Delivery and leadershipRun a retro on your own mistakes
Trace each cause, compare with a better solution, and write the rule down.
Delivery and leadershipPair on the first task in a new area, then step back
Ownership grows faster than instruction.
Delivery and leadershipGive people end-to-end ownership of a module
Including production support. It changes how they design.
Delivery and leadershipSearch before you build
Grep for the domain nouns across the whole tree. A module that does it may already exist.
Delivery and leadershipPrefer changing the data flow to adding a validation exception
Conditionals relocate edge cases. Deriving the value closes them.
Delivery and leadershipFlag stale instead of recomputing everything
A needs-resync flag is cheaper and more predictable than an expensive recompute on every save.
Delivery and leadershipKeep work on the branch the owner names
Branch hygiene is part of trust.
Delivery and leadershipNever commit secrets, never force-push main
Check status before staging. These two habits prevent most embarrassing incidents.
AI and agentsGive agents a knowledge vault
Projects, rules, decisions and a journal in plain files. Better context produces better output.
AI and agentsGive every repository one entry file
A single document that routes an agent to the notes it needs, instead of loading everything.
AI and agentsWire the same entry file into every tool
Claude, Gemini, Copilot and Cursor then share identical context.
AI and agentsSave corrections as rules
A mistake an agent makes once should not be made twice.
AI and agentsWrite skills for repeatable workflows
A written procedure turns a fragile prompt into a dependable process.
AI and agentsKeep a human in the loop at the review step
The agent drafts the timesheet and the tickets. A person approves before anything is submitted.
AI and agentsMake the agent say what it did and did not check
Verification before claims, always.
AI and agentsShow a dry-run plan before changing configuration
Tool setup, database writes and secrets all need a visible plan first.
AI and agentsNever let an agent push, or touch main, unprompted
Commit and push only when asked, on the named branch.
AI and agentsNo AI attribution in commits or pull requests
The commit identity is the owner's. State it once and enforce it everywhere.
AI and agentsKeep LLM calls on the server
Keys and tenant data never reach the browser.
AI and agentsReview personal data before sending it to an AI service
Treat the model provider as a sub-processor and record it.
AI and agentsRun LLM work off the critical path
Draft agendas, summarise orders and generate documents asynchronously.
AI and agentsUse OCR and vision where it saves typing
KYC and document flows benefit, with confidence thresholds and a human fallback.
AI and agentsExpose systems to agents through MCP, with limits
Calendar, mail and ticket access within defined permissions.
AI and agentsSeparate observation, inference and unknowns in analysis
Evidence with provenance beats confident guesses, for people and for agents.
Privacy and complianceEstablish the lawful basis before collecting data
Contract, legal obligation, legitimate interests or consent. Document it.
Privacy and complianceCollect only what you need
No just-in-case columns. Review every new field against a purpose.
Privacy and complianceKeep a retention table
Per data type: how long, and why. Financial records six years, audit logs seven, unconverted leads six months.
Privacy and complianceAutomate expiry, or schedule a purge
A retention period nobody enforces is not a policy.
Privacy and complianceBuild data subject rights as endpoints
Access, rectification, erasure, portability and objection, within the legal window.
Privacy and complianceRespect legal-obligation retention over erasure requests
Erase where the basis has lapsed, keep where the law requires.
Privacy and complianceShow each role only the data it needs
Staff see their own data, managers their team, admins their tenant.
Privacy and complianceNever expose sensitive derived data to the wrong role
Cost rates, margins and notes get their own response classes.
Privacy and complianceStrip personal data from logs
Ids in logs, details in the database, access controlled.
Privacy and complianceKeep an append-only audit log
Tenant-scoped, immutable, retained for the required period.
Privacy and complianceRecord sub-processors and what each receives
Cloud, email, payments and AI vendors, with the data they see.
Privacy and complianceRehearse the breach checklist
Scope, contain, assess, notify the regulator within 72 hours if high risk, notify people, and write it all down.