A modular application framework for Zig 0.16.0, inspired by Spring Modulith. Build scalable applications from monolithic to distributed systems with progressive architecture evolution.
| Guide | Description |
|---|---|
| Quick Start | Get started in 5 minutes |
| Best Practices | Architecture evolution from 1K to 1M+ DAU |
| API Reference | Detailed API documentation |
| Architecture | System design and patterns |
| Evaluation Report | Production readiness assessment (75/100) |
| Examples | Runnable example projects |
| ZModu CLI | Code generator for modules, ORM, APIs (npm i -g @chy3xyz/zmodu) |
- Module System β Declarative module definition with compile-time dependency validation
- Lifecycle Management β Automatic init/deinit orchestration in dependency order
- Dependency Injection β Type-safe container with compile-time hash checking (CRC32)
- Event System β TypedEventBus + DistributedEventBus + TransactionalEvent + Outbox pattern
- Application Builder β Fluent API with shutdown hooks and graceful termination
- HTTP Server β Async fiber-based server (kqueue/io_uring), trie router, middleware chains
- WebSocket β RFC 6455 server/client with origin validation and monitoring
- gRPC
β οΈ β Service registry + Proto parser + 16 status codes (experimental) - OpenAPI β 3.0/3.1 JSON document generator from route metadata
- Idempotency β Request deduplication middleware with TTL-based store
- Circuit Breaker β Three-state (closed/open/half-open) with configurable thresholds
- Rate Limiter β Token bucket with per-client overrides
- Retry Policy β Exponential backoff with configurable jitter
- Load Shedder β Adaptive concurrency limiting
- Saga Orchestrator β Automatic compensation with reverse-order rollback + step logging
- SQLx β PostgreSQL / MySQL / SQLite with connection pooling + circuit breaker
- ORM β Type-safe repository pattern with compile-time table mapping
- Database Migrations β Flyway/Liquibase-style versioned migrations with SHA256 checksums
- Cache Manager β LRU cache with TTL expiration
- Redis Client β Connection pooling and command pipeline
- Connection Pool β Generic resource pool with health checking
- DistributedEventBus β Cross-node event pub/sub with heartbeat
- ClusterMembership
β οΈ β Gossip-based node discovery + health check (experimental) - DistributedTransaction
β οΈ β 2PC + Saga patterns (experimental, needs persistence) - Kafka Connector β Producer/Consumer with topic stats + EventBridge
- Sharding β Tenant-aware ShardRouter with configurable pools
- Distributed Tracing β OpenTelemetry-compatible, Jaeger/Zipkin export
- Prometheus Metrics β Counter / Gauge (lock-free CAS) / Histogram / Summary
- Structured Logging β JSON-formatted with log rotation and levels
- Auto Instrumentation β Automatic lifecycle/event/API instrumentation
- Health Endpoints β K8s-compatible liveness/readiness/module-health probes
- JWT Authentication β Token generation/verification with expiry
- RBAC β Role-based access control
- Password Encoder β Scrypt-based password hashing
- Security Scanner β Static SAST with configurable rules
- Secrets Manager β Multi-source secrets (env > file > Vault > default) with priority resolution
- Multi-Tenancy β TenantContext + DataPermission + ShardRouter
- Architecture Tester β Compile-time dependency rule validation
- Module Interaction Verifier β Spring Modulith verify()-style interaction model checking
- Contract Testing β Pact-style consumer-driven contract verification
- Plugin System
β οΈ β Dynamic extension loading (experimental) - Web Monitor
β οΈ β HTTP dashboard for module inspection (experimental) - Hot Reloader
β οΈ β File-watch based module change detection (experimental) - CI/CD Pipeline β GitHub Actions: matrix build (linux/macOS), lint, benchmark, Docker, release
For large projects, import only the domains you need:
const zmodu = @import("zigmodu");
// Full import (everything):
var app = try zmodu.builder(allocator, io).build(.{MyModule});
// Fast import: only HTTP + Core (skips SQLx, Redis, Kafka, etc.):
const http = zmodu.http; // Server, middleware, client, OpenAPI
const data = zmodu.data; // SQLx, Redis, ORM, Cache, Migrations
const sec = zmodu.security; // Auth, RBAC, API keys, Secrets
const obs = zmodu.observability; // Prometheus, Tracing, LoggingEach domain file is self-contained β importing zmodu.http does not compile sqlx or redis.
# Install Zig 0.16.0
brew install zig@0.16.0 # macOS
# or
apt install zig=0.16.0 # Linux// src/modules/user.zig
const std = @import("std");
const zigmodu = @import("zigmodu");
const UserModule = struct {
pub const info = zigmodu.api.Module{
.name = "user",
.description = "User management module",
.dependencies = &.{},
};
pub fn init() !void {
std.log.info("User module initialized", .{});
}
pub fn deinit() void {
std.log.info("User module cleaned up", .{});
}
};// src/main.zig
const std = @import("std");
const zigmodu = @import("zigmodu");
const user = @import("modules/user.zig");
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
var modules = try zigmodu.scanModules(allocator, .{user});
defer modules.deinit();
try zigmodu.validateModules(&modules);
try zigmodu.startAll(&modules);
defer zigmodu.stopAll(&modules);
std.log.info("Application started!", .{});
}const Server = zigmodu.http_server.Server;
const Context = zigmodu.http_server.Context;
pub fn main(init: std.process.Init) !void {
var server = Server.init(init.io, init.gpa, 8080);
defer server.deinit();
try server.addRoute(.{
.method = .GET,
.path = "/health",
.handler = struct {
fn handle(ctx: *Context) anyerror!void {
try ctx.json(200, "{\"status\":\"ok\"}");
}
}.handle,
});
try server.start();
}# Start full stack (zigmodu + PostgreSQL + Redis)
docker compose up -d
# With Vault and Jaeger
docker compose --profile secrets --profile tracing up -dzigmodu/
βββ src/
β βββ root.zig # Public API (PRIMARY / ADVANCED / DEPRECATED)
β βββ Application.zig # Application builder + lifecycle
β βββ api/ # Public API types
β β βββ Module.zig # Module / Modulith structs
β β βββ Server.zig # HTTP server + router
β β βββ Middleware.zig # Middleware framework
β βββ core/ # Core framework
β β βββ Module.zig # ModuleInfo, ApplicationModules
β β βββ ModuleScanner.zig # Compile-time module scanning
β β βββ ModuleValidator.zig # Dependency validation
β β βββ ModuleInteractionVerifier.zig # Interaction model verification
β β βββ EventBus.zig # Type-safe event bus
β β βββ DistributedEventBus.zig # Cross-node event bus
β β βββ Lifecycle.zig # startAll/stopAll
β β βββ Time.zig # Monotonic time utility
β β βββ GrpcTransport.zig # gRPC service registry + proto parser
β β βββ KafkaConnector.zig # Kafka producer/consumer
β β βββ SagaOrchestrator.zig # Saga auto-compensation orchestrator
β β βββ DistributedTransaction.zig # 2PC + Saga transactions
β β βββ HealthEndpoint.zig # K8s liveness/readiness probes
β β βββ HotReloader.zig # File-watch hot reload
β β βββ PluginManager.zig # Dynamic plugin system
β β βββ ...
β βββ http/ # HTTP & API
β β βββ HttpClient.zig # HTTP client with pooling
β β βββ Idempotency.zig # Request deduplication middleware
β β βββ OpenApi.zig # OpenAPI 3.x doc generator
β βββ migration/ # Database migrations
β β βββ Migration.zig # Flyway-style migration runner
β βββ secrets/ # Secrets management
β β βββ SecretsManager.zig # Multi-source secrets with Vault
β βββ resilience/ # Resilience patterns
β β βββ CircuitBreaker.zig
β β βββ RateLimiter.zig
β β βββ Retry.zig
β β βββ LoadShedder.zig
β βββ metrics/ # Observability
β β βββ PrometheusMetrics.zig
β β βββ AutoInstrumentation.zig
β βββ tracing/ # Distributed tracing
β β βββ DistributedTracer.zig
β βββ security/ # Authentication & authorization
β β βββ SecurityModule.zig
β β βββ SecurityScanner.zig
β β βββ Rbac.zig
β β βββ PasswordEncoder.zig
β βββ tenant/ # Multi-tenancy
β β βββ TenantContext.zig
β β βββ ShardRouter.zig
β βββ sqlx/ # Database drivers
β βββ redis/ # Redis client
β βββ pool/ # Connection pool
β βββ cache/ # Cache (LRU)
β βββ scheduler/ # Task scheduler (Cron)
β βββ messaging/ # Message queue + Outbox
β βββ di/ # DI container
β βββ config/ # Configuration (JSON/YAML/TOML)
β βββ log/ # Structured logging
β βββ test/ # Testing utilities
β β βββ ContractTest.zig # Pact-style contract testing
β β βββ IntegrationTest.zig
β β βββ ModuleTest.zig
β βββ validation/ # Object validation
βββ docs/ # Documentation
βββ examples/ # Example projects
βββ shopdemo/ # Full reference app (42 modules, 152 tables)
βββ tools/zmodu/ # zmodu CLI code generator
βββ Dockerfile # Multi-stage Docker build
βββ docker-compose.yml # Full stack (PG + Redis + Vault + Jaeger)
βββ .github/workflows/ci.yml # CI/CD pipeline
ZigModu grows with your application:
| Stage | DAU | Architecture | Key Capabilities |
|---|---|---|---|
| 1 | <1K | Monolith | Module + Lifecycle |
| 2 | 1K-10K | Vertical Scale | Events + Cache |
| 3 | 10K-100K | Multi-Instance | CircuitBreaker + RateLimiter |
| 4 | 100K-1M | Distributed | DistributedEventBus + Cluster |
| 5 | >1M | Platform | HotReload + Plugins + Kafka |
See Best Practices for detailed evolution guide.
# Build
zig build
# Run tests
zig build test
# Run example
zig build run
# Generate documentation
zig build docs
# Run benchmarks
zig build benchmark
# Format code
zig fmt src/
# Docker
docker compose up -d # Start full stack
docker compose --profile tracing up -d # With Jaeger| Example | Description |
|---|---|
| Basic | Module fundamentals |
| Event-Driven | Publish-subscribe patterns |
| Testing | Test utilities |
| HTTP Stress Test | Concurrent connections |
| Metaverse Creative | Creative demo |
| Distributed | Multi-node deployment |
| ShopDemo | Full e-commerce (42 modules, 790+ APIs) |
Contributions welcome! See CONTRIBUTING.md.
git clone https://github.com/yourusername/zigmodu.git
git checkout -b feature/my-feature
zig build test
git commit -m "feat: add feature"MIT License - see LICENSE for details.