Daemon Development
Build long-running background processes that start reliably, run continuously, recover from failures, and shut down gracefully. Expert-level daemon architecture across macOS launchd, Linux systemd, and AI-powered services.
Decision Points
1. Platform-Specific Init System Choice
Platform Detected?
├─ macOS
│ ├─ Must run at boot (no user login): LaunchDaemon → /Library/LaunchDaemons/
│ ├─ User session required (GUI/files): LaunchAgent → ~/Library/LaunchAgents/
│ └─ System-wide user service: LaunchAgent → /Library/LaunchAgents/
├─ Linux
│ ├─ systemd available: systemd unit file → /etc/systemd/system/
│ ├─ Legacy SysV: init.d script (rare, avoid if possible)
│ └─ Container: s6 or built-in supervision
└─ Cross-platform dev
├─ Node.js app: pm2 for development, systemd/launchd for production
└─ Other languages: Direct systemd/launchd implementation
2. Service Type Configuration
Daemon Startup Behavior?
├─ Simple process (doesn't fork)
│ ├─ systemd: Type=simple
│ └─ launchd: Standard plist (no special keys)
├─ Signals readiness when ready
│ ├─ systemd: Type=notify + sd_notify("READY=1")
│ └─ launchd: N/A (use health check instead)
├─ Forks child process (legacy)
│ ├─ systemd: Type=forking + PIDFile (avoid)
│ └─ launchd: Not supported (rewrite to not fork)
└─ Socket-activated
├─ systemd: Type=simple + [Socket] section
└─ launchd: Sockets dict in plist
3. Restart Policy Design
Failure Recovery Strategy?
├─ Critical service (must always run)
│ ├─ systemd: Restart=always, RestartSec=5
│ └─ launchd: KeepAlive=true, ThrottleInterval=10
├─ Crash recovery only
│ ├─ systemd: Restart=on-failure
│ └─ launchd: KeepAlive={SuccessfulExit=false}
├─ Manual restart preferred
│ ├─ systemd: Restart=no
│ └─ launchd: KeepAlive=false
└─ Rate-limited restart
├─ systemd: StartLimitBurst=5, StartLimitIntervalSec=60
└─ launchd: ThrottleInterval=30 (built-in)
4. AI Daemon Rate Limiting Strategy
LLM API Connection Pattern?
├─ Single provider, token bucket
│ ├─ Token estimation: prompt_tokens + max_completion_tokens
│ ├─ Bucket refill: tokens_per_minute from provider limits
│ └─ Overflow: Queue requests with priority
├─ Multi-provider failover
│ ├─ Circuit breaker per provider (3 failures = 30s timeout)
│ ├─ Rate limit per provider independently
│ └─ Failover order: primary → secondary → queue
├─ Streaming responses
│ ├─ Reserve tokens optimistically
│ ├─ Adjust on actual_tokens in real-time
│ └─ Handle mid-stream rate limits gracefully
└─ Batch processing
├─ Group similar requests to maximize throughput
└─ Split large batches if they hit rate limits
5. Graceful Shutdown Handling
SIGTERM Received?
├─ Web server daemon
│ ├─ 1. server.close() - stop accepting new connections
│ ├─ 2. Wait for active requests (timeout: TimeoutStopSec-5s)
│ ├─ 3. Close database connections
│ └─ 4. exit(0)
├─ Queue worker daemon
│ ├─ 1. Stop polling for new jobs
│ ├─ 2. Finish current job (timeout protection)
│ ├─ 3. Flush any pending state
│ └─ 4. exit(0)
├─ AI daemon
│ ├─ 1. Stop accepting new LLM requests
│ ├─ 2. Drain in-flight requests (respect provider timeouts)
│ ├─ 3. Save rate limit state to disk
│ └─ 4. Close provider connections, exit(0)
└─ Database/stateful daemon
├─ 1. Checkpoint/flush transactions
├─ 2. Close client connections gracefully
├─ 3. Release file locks
└─ 4. exit(0)
Failure Modes
1. Restart Loop Death Spiral
- Symptoms: High CPU usage, rapid log growth, service stuck in "activating" state
- Diagnosis: Daemon crashes immediately on startup, init system restarts too quickly
- Detection:
journalctl -u service shows start/crash/start pattern every few seconds
- Fix: Add
RestartSec=10 (systemd) or ThrottleInterval=15 (launchd), implement startup validation
2. Zombie Process Accumulation
- Symptoms:
ps aux shows <defunct> processes, parent daemon still running but degraded
- Diagnosis: Daemon spawns child processes but doesn't reap them (missing SIGCHLD handler)
- Detection:
ps axo pid,ppid,stat,comm | grep Z shows zombie children
- Fix: Install SIGCHLD handler with
wait() or waitpid(), use signal(SIGCHLD, SIG_IGN) if children are fire-and-forget
3. Connection Leak Cascade
- Symptoms: "Too many open files" errors, service degrades over time, works fine after restart
- Diagnosis: File descriptors or network connections not closed properly
- Detection:
lsof -p <daemon_pid> | wc -l grows continuously, eventual EMFILE errors
- Fix: Add connection pooling with max limits, implement proper cleanup in error paths, set
LimitNOFILE in systemd
4. Log Disk Explosion
- Symptoms: Disk space alerts, daemon crashes with "No space left on device"
- Diagnosis: No log rotation configured, daemon writes unbounded logs
- Detection: Log files in GB range, df shows /var/log at 100% capacity
- Fix: Configure logrotate/newsyslog, use systemd journald with
SystemMaxUse, add log level controls
5. Rate Limit Thrash (AI Daemons)
- Symptoms: High latency, request timeouts, alternating success/failure patterns
- Diagnosis: No backoff after rate limit hits, daemon hammers API repeatedly
- Detection: Provider API returns 429 errors, response times spike periodically
- Fix: Implement exponential backoff, parse Retry-After headers, circuit breaker per provider
Worked Examples
AI Daemon Case Study: LLM Rate Limit Management
Scenario: Building an AI daemon that processes user requests through OpenAI API, needs 99.9% uptime with graceful rate limit handling.
1. Initial Architecture Decision
# Decision: Multi-provider with circuit breakers
# Primary: OpenAI GPT-4, Secondary: Anthropic Claude, Tertiary: Local model
# systemd unit file choice
Type=notify # Daemon signals when fully initialized
Restart=on-failure
RestartSec=10
2. Rate Limiting Implementation
// Token bucket per provider (expert catches: different providers = different limits)
const rateLimiters = {
openai: new TokenBucket({ tokensPerMinute: 40000, burstCapacity: 8000 }),
anthropic: new TokenBucket({ tokensPerMinute: 25000, burstCapacity: 5000 }),
};
// Novice mistake: Request-based limiting
// Expert insight: LLM APIs are token-based, not request-based
async processRequest(req: LLMRequest) {
const estimatedTokens = this.estimateTokens(req.prompt, req.maxTokens);
await this.rateLimiters.openai.acquire(estimatedTokens);
// ... proceed with API call
}
3. Circuit Breaker Configuration
// Expert trade-off: Aggressive vs Conservative failover
const circuitBreaker = new CircuitBreaker({
failureThreshold: 3, // Conservative: 5+ for stable APIs, 3 for flaky ones
timeout: 30000, // Aggressive: 15s, Conservative: 60s
resetTimeout: 60000, // How long to wait before retry
});
// Decision point: When to fail over?
if (error.status === 429) {
// Rate limited: backoff on primary, don't fail over yet
await this.exponentialBackoff(provider, error.retryAfter);
} else if (error.status >= 500) {
// Server error: immediate failover to secondary
this.circuitBreaker.recordFailure('openai');
}
4. Graceful Shutdown Pattern
// Expert catches: Race conditions in shutdown
let shutdownInProgress = false;
process.on('SIGTERM', async () => {
if (shutdownInProgress) return; // Idempotent shutdown
shutdownInProgress = true;
console.log('SIGTERM received, draining connections...');
// 1. Stop accepting new requests
server.close();
// 2. Wait for in-flight requests (with timeout)
const drainTimeout = setTimeout(() => {
console.log('Drain timeout, force exit');
process.exit(1);
}, 25000); // systemd TimeoutStopSec=30, so exit by 25s
await Promise.all([
this.drainActiveRequests(),
this.flushRateLimitState(), // Save token bucket state to disk
]);
clearTimeout(drainTimeout);
process.exit(0);
});
5. Trade-offs and Decision Results
- Aggressive restart:
RestartSec=5 for quick recovery vs RestartSec=30 to avoid thrashing
- Circuit breaker: 3 failures for failover (catches transient issues) vs 5 failures (more stable)
- Drain timeout: 25s (safe margin) vs 29s (maximize request completion)
- Result: 99.95% uptime achieved, average failover time 2.3 seconds
Quality Gates
Not-For Boundaries
This skill is NOT for:
- Container orchestration: For Kubernetes deployments, Docker Swarm, or container-specific supervision → use
devops-automator
- One-shot scheduled tasks: For cron jobs that run and exit, periodic batch processing → use
task-scheduler
- Web application deployment: For nginx/Apache configuration, reverse proxy setup, SSL termination → use
backend-architect
- Queue worker frameworks: For Sidekiq, Celery, Bull queues with built-in supervision → use
background-job-orchestrator
- Development process management: For hot-reloading, file watching, development servers → use standard dev tooling (nodemon, cargo watch)
- Database administration: For MySQL/PostgreSQL service configuration → use
database-architect
Delegate to other skills when:
- Building microservice architecture →
backend-architect handles service mesh, load balancing
- Setting up CI/CD pipelines →
devops-automator handles deployment automation
- Implementing job queues →
background-job-orchestrator handles queue-specific patterns
- Creating always-on AI agents →
always-on-agent-architecture handles AI-specific lifecycle needs
1---
2license: Apache-2.0
3name: daemon-development
4description: |
5 Build daemon/background processes that start on boot, run continuously, and manage their own lifecycle. Covers macOS launchd (plist files, agents vs daemons), Linux systemd (unit files), Windows services, process supervision, logging, health checks, graceful shutdown, auto-restart, and AI-powered daemons that manage LLM API connections and rate limits. Activate on: "daemon", "background process", "launchd", "systemd", "service file", "plist", "launch agent", "launch daemon", "auto-start", "always running", "process supervisor", "pm2", "background service", "boot service", "AI daemon", "long-running process". NOT for: container orchestration (use devops-automator), cron jobs that run and exit (use task-scheduler), web server deployment (use backend-architect).
6allowed-tools: Read,Write,Edit,Bash,Glob,Grep,WebSearch,WebFetch
7metadata:
8 source: https://skillmd.com/skills/curiositech/daemon-development
9 category: Infrastructure & DevOps
10 tags:
11 - daemon
12 - launchd
13 - systemd
14 - background-process
15 - process-supervision
16 - lifecycle
17 - devops
18 - ai-daemon
19 pairs-with:
20 - skill: always-on-agent-architecture
21 reason: Always-on agents are daemons with AI-specific lifecycle needs
22 - skill: devops-automator
23 reason: Deployment and service management overlap
24 - skill: background-job-orchestrator
25 reason: Background jobs run inside daemon processes
26category: Backend & Infrastructure
27tags:
28 - daemon
29 - background-process
30 - service
31 - system-programming
32 - linux
33---
34
35# Daemon Development
36
37Build long-running background processes that start reliably, run continuously, recover from failures, and shut down gracefully. Expert-level daemon architecture across macOS launchd, Linux systemd, and AI-powered services.
38
39## Decision Points
40
41### 1. Platform-Specific Init System Choice
42```
43Platform Detected?
44├─ macOS
45│ ├─ Must run at boot (no user login): LaunchDaemon → /Library/LaunchDaemons/
46│ ├─ User session required (GUI/files): LaunchAgent → ~/Library/LaunchAgents/
47│ └─ System-wide user service: LaunchAgent → /Library/LaunchAgents/
48├─ Linux
49│ ├─ systemd available: systemd unit file → /etc/systemd/system/
50│ ├─ Legacy SysV: init.d script (rare, avoid if possible)
51│ └─ Container: s6 or built-in supervision
52└─ Cross-platform dev
53 ├─ Node.js app: pm2 for development, systemd/launchd for production
54 └─ Other languages: Direct systemd/launchd implementation
55```
56
57### 2. Service Type Configuration
58```
59Daemon Startup Behavior?
60├─ Simple process (doesn't fork)
61│ ├─ systemd: Type=simple
62│ └─ launchd: Standard plist (no special keys)
63├─ Signals readiness when ready
64│ ├─ systemd: Type=notify + sd_notify("READY=1")
65│ └─ launchd: N/A (use health check instead)
66├─ Forks child process (legacy)
67│ ├─ systemd: Type=forking + PIDFile (avoid)
68│ └─ launchd: Not supported (rewrite to not fork)
69└─ Socket-activated
70 ├─ systemd: Type=simple + [Socket] section
71 └─ launchd: Sockets dict in plist
72```
73
74### 3. Restart Policy Design
75```
76Failure Recovery Strategy?
77├─ Critical service (must always run)
78│ ├─ systemd: Restart=always, RestartSec=5
79│ └─ launchd: KeepAlive=true, ThrottleInterval=10
80├─ Crash recovery only
81│ ├─ systemd: Restart=on-failure
82│ └─ launchd: KeepAlive={SuccessfulExit=false}
83├─ Manual restart preferred
84│ ├─ systemd: Restart=no
85│ └─ launchd: KeepAlive=false
86└─ Rate-limited restart
87 ├─ systemd: StartLimitBurst=5, StartLimitIntervalSec=60
88 └─ launchd: ThrottleInterval=30 (built-in)
89```
90
91### 4. AI Daemon Rate Limiting Strategy
92```
93LLM API Connection Pattern?
94├─ Single provider, token bucket
95│ ├─ Token estimation: prompt_tokens + max_completion_tokens
96│ ├─ Bucket refill: tokens_per_minute from provider limits
97│ └─ Overflow: Queue requests with priority
98├─ Multi-provider failover
99│ ├─ Circuit breaker per provider (3 failures = 30s timeout)
100│ ├─ Rate limit per provider independently
101│ └─ Failover order: primary → secondary → queue
102├─ Streaming responses
103│ ├─ Reserve tokens optimistically
104│ ├─ Adjust on actual_tokens in real-time
105│ └─ Handle mid-stream rate limits gracefully
106└─ Batch processing
107 ├─ Group similar requests to maximize throughput
108 └─ Split large batches if they hit rate limits
109```
110
111### 5. Graceful Shutdown Handling
112```
113SIGTERM Received?
114├─ Web server daemon
115│ ├─ 1. server.close() - stop accepting new connections
116│ ├─ 2. Wait for active requests (timeout: TimeoutStopSec-5s)
117│ ├─ 3. Close database connections
118│ └─ 4. exit(0)
119├─ Queue worker daemon
120│ ├─ 1. Stop polling for new jobs
121│ ├─ 2. Finish current job (timeout protection)
122│ ├─ 3. Flush any pending state
123│ └─ 4. exit(0)
124├─ AI daemon
125│ ├─ 1. Stop accepting new LLM requests
126│ ├─ 2. Drain in-flight requests (respect provider timeouts)
127│ ├─ 3. Save rate limit state to disk
128│ └─ 4. Close provider connections, exit(0)
129└─ Database/stateful daemon
130 ├─ 1. Checkpoint/flush transactions
131 ├─ 2. Close client connections gracefully
132 ├─ 3. Release file locks
133 └─ 4. exit(0)
134```
135
136## Failure Modes
137
138### 1. **Restart Loop Death Spiral**
139- **Symptoms**: High CPU usage, rapid log growth, service stuck in "activating" state
140- **Diagnosis**: Daemon crashes immediately on startup, init system restarts too quickly
141- **Detection**: `journalctl -u service` shows start/crash/start pattern every few seconds
142- **Fix**: Add `RestartSec=10` (systemd) or `ThrottleInterval=15` (launchd), implement startup validation
143
144### 2. **Zombie Process Accumulation**
145- **Symptoms**: `ps aux` shows `<defunct>` processes, parent daemon still running but degraded
146- **Diagnosis**: Daemon spawns child processes but doesn't reap them (missing SIGCHLD handler)
147- **Detection**: `ps axo pid,ppid,stat,comm | grep Z` shows zombie children
148- **Fix**: Install SIGCHLD handler with `wait()` or `waitpid()`, use `signal(SIGCHLD, SIG_IGN)` if children are fire-and-forget
149
150### 3. **Connection Leak Cascade**
151- **Symptoms**: "Too many open files" errors, service degrades over time, works fine after restart
152- **Diagnosis**: File descriptors or network connections not closed properly
153- **Detection**: `lsof -p <daemon_pid> | wc -l` grows continuously, eventual EMFILE errors
154- **Fix**: Add connection pooling with max limits, implement proper cleanup in error paths, set `LimitNOFILE` in systemd
155
156### 4. **Log Disk Explosion**
157- **Symptoms**: Disk space alerts, daemon crashes with "No space left on device"
158- **Diagnosis**: No log rotation configured, daemon writes unbounded logs
159- **Detection**: Log files in GB range, df shows /var/log at 100% capacity
160- **Fix**: Configure logrotate/newsyslog, use systemd journald with `SystemMaxUse`, add log level controls
161
162### 5. **Rate Limit Thrash (AI Daemons)**
163- **Symptoms**: High latency, request timeouts, alternating success/failure patterns
164- **Diagnosis**: No backoff after rate limit hits, daemon hammers API repeatedly
165- **Detection**: Provider API returns 429 errors, response times spike periodically
166- **Fix**: Implement exponential backoff, parse Retry-After headers, circuit breaker per provider
167
168## Worked Examples
169
170### AI Daemon Case Study: LLM Rate Limit Management
171
172**Scenario**: Building an AI daemon that processes user requests through OpenAI API, needs 99.9% uptime with graceful rate limit handling.
173
174**1. Initial Architecture Decision**
175```bash
176# Decision: Multi-provider with circuit breakers
177# Primary: OpenAI GPT-4, Secondary: Anthropic Claude, Tertiary: Local model
178
179# systemd unit file choice
180Type=notify # Daemon signals when fully initialized
181Restart=on-failure
182RestartSec=10
183```
184
185**2. Rate Limiting Implementation**
186```typescript
187// Token bucket per provider (expert catches: different providers = different limits)
188const rateLimiters = {
189 openai: new TokenBucket({ tokensPerMinute: 40000, burstCapacity: 8000 }),
190 anthropic: new TokenBucket({ tokensPerMinute: 25000, burstCapacity: 5000 }),
191};
192
193// Novice mistake: Request-based limiting
194// Expert insight: LLM APIs are token-based, not request-based
195async processRequest(req: LLMRequest) {
196 const estimatedTokens = this.estimateTokens(req.prompt, req.maxTokens);
197 await this.rateLimiters.openai.acquire(estimatedTokens);
198 // ... proceed with API call
199}
200```
201
202**3. Circuit Breaker Configuration**
203```typescript
204// Expert trade-off: Aggressive vs Conservative failover
205const circuitBreaker = new CircuitBreaker({
206 failureThreshold: 3, // Conservative: 5+ for stable APIs, 3 for flaky ones
207 timeout: 30000, // Aggressive: 15s, Conservative: 60s
208 resetTimeout: 60000, // How long to wait before retry
209});
210
211// Decision point: When to fail over?
212if (error.status === 429) {
213 // Rate limited: backoff on primary, don't fail over yet
214 await this.exponentialBackoff(provider, error.retryAfter);
215} else if (error.status >= 500) {
216 // Server error: immediate failover to secondary
217 this.circuitBreaker.recordFailure('openai');
218}
219```
220
221**4. Graceful Shutdown Pattern**
222```typescript
223// Expert catches: Race conditions in shutdown
224let shutdownInProgress = false;
225
226process.on('SIGTERM', async () => {
227 if (shutdownInProgress) return; // Idempotent shutdown
228 shutdownInProgress = true;
229
230 console.log('SIGTERM received, draining connections...');
231
232 // 1. Stop accepting new requests
233 server.close();
234
235 // 2. Wait for in-flight requests (with timeout)
236 const drainTimeout = setTimeout(() => {
237 console.log('Drain timeout, force exit');
238 process.exit(1);
239 }, 25000); // systemd TimeoutStopSec=30, so exit by 25s
240
241 await Promise.all([
242 this.drainActiveRequests(),
243 this.flushRateLimitState(), // Save token bucket state to disk
244 ]);
245
246 clearTimeout(drainTimeout);
247 process.exit(0);
248});
249```
250
251**5. Trade-offs and Decision Results**
252- **Aggressive restart**: `RestartSec=5` for quick recovery vs `RestartSec=30` to avoid thrashing
253- **Circuit breaker**: 3 failures for failover (catches transient issues) vs 5 failures (more stable)
254- **Drain timeout**: 25s (safe margin) vs 29s (maximize request completion)
255- **Result**: 99.95% uptime achieved, average failover time 2.3 seconds
256
257## Quality Gates
258
259- [ ] Boot test passes: Service starts automatically after system reboot
260- [ ] Log rotation configured: Logs rotate daily/weekly, old logs purged, no disk space growth
261- [ ] SIGTERM handling verified: Graceful shutdown completes within TimeoutStopSec
262- [ ] Health endpoint responds: HTTP 200 with meaningful status (uptime, queue depth, dependencies)
263- [ ] Restart backoff works: Service doesn't enter tight restart loop on immediate crash
264- [ ] Resource limits enforced: Memory/CPU/file descriptor limits prevent resource exhaustion
265- [ ] Non-root execution: Service runs as dedicated user with minimal privileges
266- [ ] Config reload tested: SIGHUP reloads configuration without full restart
267- [ ] Crash recovery verified: Process crash triggers automatic restart within RestartSec
268- [ ] Security hardening applied: NoNewPrivileges, ProtectSystem, ReadWritePaths configured
269- [ ] For AI daemons: Token-based rate limiting implemented with proper estimation
270- [ ] For AI daemons: Provider failover works when primary returns 5xx errors
271
272## Not-For Boundaries
273
274**This skill is NOT for:**
275- **Container orchestration**: For Kubernetes deployments, Docker Swarm, or container-specific supervision → use `devops-automator`
276- **One-shot scheduled tasks**: For cron jobs that run and exit, periodic batch processing → use `task-scheduler`
277- **Web application deployment**: For nginx/Apache configuration, reverse proxy setup, SSL termination → use `backend-architect`
278- **Queue worker frameworks**: For Sidekiq, Celery, Bull queues with built-in supervision → use `background-job-orchestrator`
279- **Development process management**: For hot-reloading, file watching, development servers → use standard dev tooling (nodemon, cargo watch)
280- **Database administration**: For MySQL/PostgreSQL service configuration → use `database-architect`
281
282**Delegate to other skills when:**
283- Building microservice architecture → `backend-architect` handles service mesh, load balancing
284- Setting up CI/CD pipelines → `devops-automator` handles deployment automation
285- Implementing job queues → `background-job-orchestrator` handles queue-specific patterns
286- Creating always-on AI agents → `always-on-agent-architecture` handles AI-specific lifecycle needs