惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 【当耐特】
Latest news
Latest news
IT之家
IT之家
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
LangChain Blog
腾讯CDC
J
Java Code Geeks
GbyAI
GbyAI
美团技术团队
V
Visual Studio Blog
Apple Machine Learning Research
Apple Machine Learning Research
Recorded Future
Recorded Future
U
Unit 42
Jina AI
Jina AI
月光博客
月光博客
罗磊的独立博客
I
InfoQ
有赞技术团队
有赞技术团队
B
Blog RSS Feed
The Register - Security
The Register - Security
WordPress大学
WordPress大学
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
MongoDB | Blog
MongoDB | Blog
NISL@THU
NISL@THU
S
Security Archives - TechRepublic
雷峰网
雷峰网
O
OpenAI News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Y
Y Combinator Blog
G
GRAHAM CLULEY
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
L
LINUX DO - 热门话题
H
Help Net Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
Securelist
P
Proofpoint News Feed
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 叶小钗
Security Latest
Security Latest
A
About on SuperTechFans
G
Google Developers Blog
T
Troy Hunt's Blog
小众软件
小众软件
H
Hacker News: Front Page
C
Cisco Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
LINUX DO - 最新话题
大猫的无限游戏
大猫的无限游戏
Webroot Blog
Webroot Blog

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Saga Pattern vs Two-Phase Commit: Distributed Transactions Without The Lies Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop
Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
The Practica · 2022-07-22 · via The Practical Developer

The deploy script printed Done. and exited 0. The new version was not actually deployed. Your monitoring alert fires four minutes later when the old pods drain and there is nothing to take their place. Somebody opens the postmortem and writes “the script reported success even though the upload failed.” It is the most common bug in shell, and the fix is three characters longer than the broken version.

Bash defaults are not safe. By default, a failed command does not stop the script. By default, an unset variable expands to empty string. By default, a pipeline returns the exit code of only the last command. Every one of those defaults will eventually bite you, and the cost of fixing them is one line at the top of the file.

#!/usr/bin/env bash
set -euo pipefail

That is the line. The rest of this post is what each flag means, the traps that come with them, and the pattern for writing scripts that actually fail when something fails.

What -e, -u, and pipefail actually do

-e (errexit). Exit immediately if any command exits non-zero. Without it, this happens:

#!/usr/bin/env bash
cp build/app.tar.gz s3://my-bucket/   # ← typo: should be aws s3 cp
echo "Upload complete"
exit 0

cp does not understand s3:// URLs and exits with code 1. Without -e, bash keeps going, prints “Upload complete”, and exits 0. Your CI pipeline reports green. Your users get the old build. With -e, the script exits the moment cp fails, and CI goes red.

-u (nounset). Exit if you reference an undefined variable. Without it:

DEPLOY_ENV=prod
rsync -av build/ user@$DEPOY_ENV.example.com:/srv/   # ← typo: DEPOY vs DEPLOY

Bash silently treats $DEPOY_ENV as empty string. The command becomes rsync -av build/ user@.example.com:/srv/. With -u, it fails immediately: DEPOY_ENV: unbound variable. Most “the script ran on staging” mysteries are this exact bug.

-o pipefail. The exit code of a pipeline is the exit code of the last command that failed, not just the last command in the chain. Without it:

curl https://flaky-api/data | jq '.items[]' > out.json

If curl fails (DNS error, 500), it exits non-zero. But jq happily reads its empty stdin, exits 0, and the pipeline reports success. With pipefail, the pipeline exits with curl’s code and -e then kicks in.

The combination is so common that it has a name: “bash strict mode.” It was popularized by Aaron Maxwell’s post in 2014 and has been the right default ever since.

The IFS line you have probably seen too

Some teams add a fourth line:

IFS=$'\n\t'

This narrows the field-splitting separator to newline and tab. Defaults to space + tab + newline, which means filenames with spaces (My Document.pdf) silently split into two arguments. With the narrower IFS:

for f in $(ls /uploads); do
  process "$f"
done

…is less dangerous, but the right answer is still to avoid $(ls) and use globs:

for f in /uploads/*; do
  process "$f"
done

I include IFS=$'\n\t' only in scripts that actually parse newline-separated input. Most scripts do not, and the IFS change can confuse maintainers.

The traps -e has

-e is not magic. There are four cases where it does not stop the script, and forgetting them is how people decide it does not work and stop using it.

Failure inside if / && / || / !. -e is suppressed when the command’s exit code is being inspected for control flow:

if grep "ERROR" log.txt; then    # ← grep failure here is fine, that is the point
  alert
fi
some_command_that_might_fail    # ← this one will trigger -e normally

That is correct behavior. But:

do_step_one && do_step_two       # ← if do_step_one fails, do_step_two is skipped
                                 #   and the script DOES NOT exit. Surprise.

Most developers expect the script to die after a failed &&. It does not. Use plain sequencing:

do_step_one
do_step_two

Failure in command substitution that is assigned to a variable:

result=$(command_that_fails)     # ← bash 4.x: -e does NOT trigger here
echo "result=$result"

This is the bug. The script keeps going with result="". Bash 5+ fixed this when shopt -s inherit_errexit is set:

set -euo pipefail
shopt -s inherit_errexit

If you write deploy scripts and you can rely on bash 5, add this line.

Failure in functions called as part of a chain. A function whose last command fails returns that exit code, but if you call it like func || true you have suppressed the error.

Background processes. cmd & does not trip -e because bash does not wait for it. If you launch background work, you must wait and check $? yourself.

A deploy-script template that fails honestly

Here is a real template I have used, end-to-end. It is annotated so you can see why each line is there.

#!/usr/bin/env bash
# Deploy frontend to staging or prod.

set -euo pipefail
shopt -s inherit_errexit         # bash 5+: catch failures in $(subshells)

# All required env vars listed up front so the script fails immediately
# if anything is missing. Without -u this would silently use empty strings.
: "${ENV:?ENV must be set: staging or prod}"
: "${BUILD_DIR:?BUILD_DIR must be set}"
: "${S3_BUCKET:?S3_BUCKET must be set}"

# Trap to print where we died on any error. Worth its weight in gold during
# 3 a.m. debugging. You get the line number, not just "exit 1".
trap 'echo "ERROR: command failed at ${BASH_SOURCE[0]}:${LINENO}: ${BASH_COMMAND}" >&2' ERR

# Sanity check: are we on a clean tree? Refuse to deploy uncommitted changes.
if [[ -n $(git status --porcelain) ]]; then
  echo "refusing to deploy: uncommitted changes" >&2
  exit 1
fi

# Build outside the deploy step so build failures stop us BEFORE we touch prod.
echo "==> building"
npm ci
npm run build

echo "==> uploading to s3://${S3_BUCKET}/${ENV}/"
aws s3 sync "${BUILD_DIR}/" "s3://${S3_BUCKET}/${ENV}/" \
  --delete \
  --cache-control "public, max-age=31536000, immutable" \
  --exclude "index.html"

# index.html gets a different cache header; separate command on purpose.
aws s3 cp "${BUILD_DIR}/index.html" "s3://${S3_BUCKET}/${ENV}/index.html" \
  --cache-control "public, max-age=60, must-revalidate"

echo "==> invalidating CDN"
aws cloudfront create-invalidation \
  --distribution-id "${CLOUDFRONT_ID}" \
  --paths "/index.html" >/dev/null

echo "==> deploy complete: $(git rev-parse --short HEAD) → ${ENV}"

A few things that are deliberate.

: "${VAR:?message}" is a parameter expansion that aborts if VAR is unset or empty. It is the only one-liner that gives you a nice error and uses -u-style behavior.

The trap '... ERR' line is the difference between a useful error message and exit 1. With it, when something fails you see:

ERROR: command failed at deploy.sh:23: aws s3 sync /build/ s3://...

You know which line, which command, and which file. Without it, you know only that something exited 1.

aws s3 sync and the index.html copy are split because they need different Cache-Control headers. People often combine them and then wonder why a deploy never goes live, because the browser is happily serving an index.html cached for a year.

Test it before you trust it

A strict-mode script lulls you into thinking it cannot fail silently. It still can if you do not exercise the failure paths. The smallest thing you can do is run the script with a deliberate fault injection:

# Force the upload to fail. Does the script actually stop?
S3_BUCKET=does-not-exist ENV=staging BUILD_DIR=./dist ./deploy.sh
echo "exit code: $?"

If the exit code is 0, you have a bug somewhere, probably an || true that should not be there, or a piped command without pipefail.

I also like running shellcheck in CI:

- name: shellcheck
  run: shellcheck deploy.sh

Shellcheck will flag the common foot-guns automatically: unquoted expansions, $(ls), [ ] vs [[ ]], missing set -e. It pays for itself the first time it catches a typo before it gets to staging.

When to stop using bash

Strict mode does not turn bash into a real programming language. It just stops the script from lying to you. Once a script gets past ~150 lines, has loops with branching logic, or talks to two or more external systems, write it in Python or Go. The reason is not bash performance; it is that a bug in 200 lines of bash takes longer to find than the same bug in 200 lines of Python.

A useful rule: if you are writing a function that takes more than three arguments, or you are using eval, or you are doing arithmetic with bc, you have outgrown bash. Move it.

The takeaway

Three characters at the top of every deploy script (-e, -u, pipefail) are the difference between “script reported success” and “script actually succeeded.” Add inherit_errexit if you can rely on bash 5. Add a trap '... ERR' so failures point at the line that broke. Validate required env vars at the top with ${VAR:?...}. Lint the script with shellcheck.

It is a small ritual. It is also the difference between a deploy you can leave running while you eat lunch and a deploy that requires a postmortem.


A note from Yojji

The unglamorous discipline of “your deploy script must fail loudly when something is wrong” is one of those things that does not show up on a roadmap and decides whether your team is paged at 3 a.m. or sleeping. It is the kind of detail Yojji’s engineers have built into the deployment pipelines they run for clients across Europe, the US, and the UK.

Yojji is an international custom software development company founded in 2016, focused on the JavaScript stack (React, Node.js, TypeScript) and cloud platforms (AWS, Azure, GCP). Their full-cycle teams cover discovery, design, development, QA, and DevOps, including the boring-but-critical scripts and pipelines that separate “we shipped” from “we shipped, and we know it shipped.”