zig-principal-engineer
Principal/Senior-level Zig playbook for backend services, systems-aware APIs, memory management, concurrency, performance, reliability, observability, and production operations. Use when: building or reviewing Zig services, designing low-level backend components, optimizing latency-sensitive services, hardening memory-sensitive systems, debugging allocator issues, or preparing Zig applications for production.
What this skill does
# Zig Mastery (Senior → Principal)
## Operate
- Start by confirming: Zig version, target OS/arch, deployment model, latency and memory goals, FFI requirements, concurrency model, and the definition of done.
- Prefer small vertical slices with explicit ownership, allocator strategy, and error paths.
- Keep the design boring and operable: simple boundaries, measurable behavior, and predictable cleanup beat clever abstractions.
- Treat memory, failure handling, and observability as first-class design constraints, not afterthoughts.
> The goal is not just "fast Zig". The goal is a backend that stays correct under pressure, exposes predictable failure modes, and remains maintainable by the next engineer.
## Default Standards
- Keep transport, domain, and infrastructure boundaries explicit.
- Choose allocator strategy intentionally and document ownership at boundaries.
- Propagate errors with context; do not hide them behind catch-all defaults.
- Prefer explicit resource lifecycle management with `defer` and `errdefer`.
- Avoid hidden global state; inject dependencies and configuration explicitly.
- Treat outbound IO, parsing, and serialization as untrusted work: set limits, timeouts, and validation rules.
- Use the standard library first unless a dependency clearly improves correctness or delivery speed.
## “Bad vs Good” (common production pitfalls)
```zig
// ❌ BAD: allocator choice is implicit and cleanup is forgotten.
const data = try fetchUsers();
process(data);
// ✅ GOOD: allocator ownership and cleanup are explicit.
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const data = try fetchUsers(allocator);
try process(data);
```
```zig
// ❌ BAD: panic-style behavior for recoverable backend failures.
const body = request.reader().readAllAlloc(allocator, max_size) catch unreachable;
// ✅ GOOD: map recoverable errors explicitly.
const body = request.reader().readAllAlloc(allocator, max_size) catch |err| switch (err) {
error.StreamTooLong => return AppError.payload_too_large,
else => return AppError.bad_request,
};
```
```zig
// ❌ BAD: fire-and-forget thread with no owner or shutdown path.
_ = try std.Thread.spawn(.{}, runWorker, .{});
// ✅ GOOD: thread lifecycle belongs to a supervisor.
const worker = try std.Thread.spawn(.{}, runWorker, .{shutdown_signal});
defer worker.join();
```
## Workflow (Feature / Refactor / Bug)
1. Reproduce behavior or codify it with a failing test.
2. Decide boundaries: protocol, orchestration, domain logic, persistence, and external integrations.
3. Define allocator strategy, ownership, and cleanup rules.
4. Implement the smallest end-to-end slice.
5. Validate tests, formatting, release behavior, and operational guardrails.
6. Review latency, allocations, failure modes, and shutdown behavior before release.
## Validation Commands
- Run `zig fmt .`.
- Run `zig test src/main.zig` or the relevant test targets.
- Run `zig build test` if the project uses a build graph.
- Run `zig build -Doptimize=ReleaseSafe` before release validation.
- Run smoke tests against the compiled binary in a production-like environment.
- Run container build validation if the service is deployed via Docker.
## Backend Architecture Guardrails
- Prefer a modular monolith before inventing service sprawl.
- Keep HTTP or TCP transport thin; map protocol concerns at the edge.
- Make timeouts, retries, backoff, and circuit breaking explicit for outbound calls.
- Bound request size, parsing depth, and connection counts.
- Treat memory pressure as an operational event: measure allocations and cap untrusted workloads.
- Every background thread or async task needs an owner, stop condition, and failure-reporting path.
## Reliability and Operations
- Expose `/health` and `/ready` style endpoints if the service runs behind orchestration.
- Use structured logs with request IDs and stable fields.
- Implement graceful shutdown: stop accepting traffic, drain in-flight work, release resources, and join workers.
- Prefer idempotent handlers where retries may occur.
- Benchmark hot paths before micro-optimizing.
## Security Checklist (Minimum)
- Validate all untrusted input lengths, counts, and encodings.
- Use allowlists for outbound destinations in sensitive environments.
- Never log secrets, credentials, or raw sensitive payloads.
- Use parameterized queries and least-privilege credentials for data stores.
- Keep unsafe FFI boundaries isolated and well-tested.
## Decision Heuristics
```text
Choose Zig when:
- predictable memory behavior matters
- latency and binary size matter
- you need more control than Go/JavaScript typically provide
- C interop is part of the system boundary
Prefer another backend stack when:
- the team needs a richer web ecosystem immediately
- delivery speed depends on mature framework conventions
- the problem is primarily CRUD with little systems-level pressure
```
## References
- Architecture and dependency direction: [references/architecture.md](references/architecture.md)
- Allocator strategy and memory ownership: [references/allocators-and-memory.md](references/allocators-and-memory.md)
- HTTP service design and reliability: [references/http-and-reliability.md](references/http-and-reliability.md)
- FFI and unsafe boundary control: [references/ffi-and-unsafe-boundaries.md](references/ffi-and-unsafe-boundaries.md)
- Testing and debugging: [references/testing-and-debugging.md](references/testing-and-debugging.md)
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.