Long-running process

On this page 7

A long-running process is a program that is started once and then runs continuously for hours, days or months, waiting for and handling work instead of exiting after a single task. On servers, it is the dominant execution model for services & processes such as web servers, database engines, message brokers and application runtimes, and its design determines how a system behaves under load, during failures and across deployments.

The concept contrasts with short-lived processes, such as a CGI script or a command-line tool, which start, complete one unit of work and terminate. Because a long-running process accumulates state over time, it brings specific concerns: memory growth, resource leaks, supervision, signal handling and safe restarts.

How a long-running process stays alive

A long-running process stays alive by entering an event loop or a blocking wait after initialization, so that it consumes little CPU while idle and wakes only when work arrives. Typical wake-up sources are incoming network connections on a bound port, messages on a queue, timer expirations and operating system signals.

The lifecycle has distinct phases. At startup, the process loads configuration, opens files, binds sockets and warms caches. In the steady state, it serves requests repeatedly with already allocated resources, which is why it achieves far lower per-request latency than a process that must initialize for every request. At shutdown, it should stop accepting new work, finish or hand off in-flight work and release resources.

The following table summarizes the lifecycle phases and what can go wrong in each.

PhaseMain activityTypical failure
StartupLoad configuration, bind ports, open poolsPort already in use, missing secret
Steady stateServe requests from an event loopMemory leak, descriptor exhaustion
ReloadReread configuration without exitPartial reload, inconsistent state
ShutdownDrain connections, flush buffersKilled before data is flushed
Lifecycle phases of a long-running process

Forms of long-running processes on servers

Long-running processes appear in several forms that differ mainly in who starts them and how they receive work. The classic Unix daemon detaches from the terminal and runs in the background, while modern deployments usually keep the process in the foreground and let a process supervisor such as systemd, Supervisord or PM2 manage it.

Many server applications combine a master process with worker processes. In the prefork model, a master binds the listening socket and forks several workers that accept connections, so a crash in one worker does not take down the whole service. Queue consumers that execute background jobs are also long-running processes, although each job they handle may be short.

FormWork sourceExample
Network daemonConnections on a bound portWeb server, SSH server
Worker poolConnections handed off by a masterPrefork application server
Queue consumerMessages from a brokerBackground job worker
SchedulerInternal timersCron-like task runner
Stream processorContinuous event streamLog or metrics pipeline
Common forms and their work sources

Long-running versus short-lived execution

The choice between long-running and short-lived execution is a trade-off between efficiency and isolation. A long-running process amortizes startup cost across millions of requests, keeps connection pools and caches warm and supports persistent connections such as WebSockets. A short-lived process starts clean every time, so leaks and corrupted state disappear when it exits.

Serverless functions sit between the two models: the platform may reuse a warm instance for many invocations but can terminate it at any moment, so code must not rely on in-memory state surviving between calls.

PropertyLong-running processShort-lived process
Startup costPaid oncePaid on every invocation
Per-request latencyLow and stableHigher, includes initialization
State between requestsKept in memoryLost at exit
Leak impactAccumulates over timeCleared at exit
Persistent connectionsSupportedImpractical
Operational needSupervision and restartsInvocation mechanism only
Comparison of execution models

Operating a long-running process reliably

Reliable operation depends on supervision, observability and controlled restarts. A supervisor restarts the process when it exits unexpectedly, applies a service restart policy with backoff to avoid a crash loop and records the process ID so that signals reach the right target.

The process itself must cooperate. It should handle SIGTERM for graceful shutdown, typically completing in-flight requests within a timeout of 10 to 30 seconds before the supervisor escalates to SIGKILL. Many daemons also treat SIGHUP as a configuration reload signal. Health endpoints and heartbeats allow a watchdog to detect a hung process that is still alive but no longer doing useful work.

  • Expose liveness and readiness checks so that orchestrators distinguish a stuck process from one that is still warming up.
  • Track resident memory, open file descriptors and thread count over days, not minutes, because slow growth is the typical signature of a leak.
  • Use rolling restarts across several instances so that deployments never remove all capacity at once.
  • Log to standard output or a structured sink so that logs survive restarts and rotation.

Common failure modes and remedies

Most problems with long-running processes come from resources that are acquired but never released. Effects that are invisible in a five-minute test become critical after two weeks of uptime, which is why load tests for such services should include soak tests lasting many hours.

SymptomLikely causeRemedy
Steadily rising memoryMemory leak or unbounded cacheBound caches, profile heap, recycle workers
Error: too many open filesDescriptor leakClose sockets and files, raise limits carefully
Process alive but unresponsiveDeadlock or blocked event loopWatchdog timer, thread dumps
Repeated restarts within secondsCrash loop at startupBackoff policy, fix configuration
Stale configuration after changeNo reload handlingImplement SIGHUP or restart cleanly
Symptoms, causes and fixes

A pragmatic safeguard is periodic worker recycling, where a worker exits after a fixed number of requests and is replaced by a fresh one. It hides rather than fixes leaks, so it should complement profiling, not replace it.

A plain-language summary

A long-running process is a program that is switched on once and then keeps working without stopping, much like a shop that stays open all day instead of opening its doors for each customer and closing again afterward. Because it is already open, it can serve each visitor quickly.

The price is upkeep. Over a long day, small messes pile up, so the program needs someone to watch it and restart it safely when it slows down or breaks. That watcher is usually a supervisor program on the server.

An example from practice

An online retailer runs its checkout API as eight long-running worker processes behind a load balancer on two Linux servers, managed by systemd. Each worker keeps a pool of twenty database connections open, so a typical request completes in about 40 milliseconds instead of the 300 milliseconds it took when a new process started per request.

After a release, monitoring shows resident memory per worker rising by roughly 50 megabytes per day. The team adds a recycling limit of 50,000 requests per worker as an immediate safeguard and uses heap profiling to find an unbounded in-memory cache of product images. Once the cache is given a size limit, memory stays flat across a 14-day soak test, and deployments continue as rolling restarts with a 20-second drain period, so customers never see failed checkouts.