kazuma-fast
v1.0.2
Published
Ultra-high-performance Node.js backend framework powered by hyper-express.
Maintainers
Readme
Kazuma Framework
Kazuma is an ultra-high-performance, enterprise-grade backend HTTP framework for Node.js. Architected upon the blazingly fast hyper-express and uWebSockets.js C++ bindings, Kazuma delivers unparalleled request throughput while offering an elegant, highly modular API modeled around the Onion Middleware Architecture.
Designed strictly for extreme backend performance and enterprise scalability, Kazuma prioritizes asynchronous non-blocking execution, native schema validation, and built-in security peripherals without the overhead of traditional web frameworks.
Core Features
- Extreme Performance: Powered by C++ WebSockets and HTTP bindings, consistently outperforming Fastify, Koa, and Express by significant margins.
- Onion Architecture Pipeline: Sequential, predictable, and strictly controlled middleware execution using modern asynchronous context bridging.
- Modular Sub-Routing: Dedicated
KazumaRouterclass for splitting large API surfaces into manageable, logical file modules. - Native Rate Limiting: Built-in DDoS and brute-force mitigation powered by memory-efficient token bucket algorithms.
- Pre-compiled JSON Validation: Just-In-Time (JIT) schema compilation using
ajvattached directly to route definitions for zero-overhead validation. - Asynchronous File Uploads: Integrated multipart and form-data parsing utilizing stream-based architecture to prevent memory exhaustion.
- Global Error Interception: Centralized error handling hook to gracefully catch, log, and format unexpected runtime exceptions across the entire pipeline.
- Dependency Injection: Native mechanisms to inject and share global states (e.g., Database Connections) and request-scoped contexts securely.
Installation
Ensure you are operating on Node.js version 22 or higher to guarantee ABI compatibility with the underlying C++ bindings.
npm install kazuma-fastQuick Start Initialization
Construct a highly performant API server with built-in security constraints.
import Kazuma from 'kazuma-fast';
const app = new Kazuma();
// Enable Cross-Origin Resource Sharing
app.cors({ origin: '*' });
// Enforce strict Rate Limiting (100 requests per 60 seconds per IP)
app.rateLimit({ points: 100, duration: 60 });
// Register an operational health check route
app.get('/api/health', (ctx) => {
ctx.status(200).json({ status: 'operational' });
});
app.listen(8080, () => {
console.log('Kazuma server is actively listening on port 8080');
});Architectural Concepts
The Context Object (ctx)
Kazuma abstracts the underlying HTTP Request and Response primitives into a unified Context object, securely passed to every middleware and route handler within the pipeline.
ctx.method: The HTTP method (e.g., 'GET', 'POST').ctx.url: The request URL path.ctx.params: Parsed dynamic path parameters.ctx.body: The asynchronously parsed and sanitized payload (JSON, urlencoded, or multipart).ctx.state: A volatile memory object used for safely passing request-scoped data between sequential middleware.ctx.app: A direct reference to the parent Kazuma Application instance, granting access to global decorators.ctx.status(code): Configures the HTTP status code. Returns the context instance for method chaining.ctx.json(data): Serializes a JavaScript object to JSON and finalizes the HTTP response.ctx.send(text): Transmits a plain text response and finalizes the HTTP response.ctx.req/ctx.res: Raw access to the underlyinghyper-expressRequest and Response objects for advanced manipulation.
Middleware Pipeline (Onion Architecture)
Kazuma enforces strict sequential execution of middleware. Developers can construct powerful asynchronous interceptors that execute logic both before and after the route handler.
app.use(async (ctx, next) => {
const start = process.hrtime.bigint();
// Yield control to the subsequent middleware or route handler
await next();
// Control flow returns here post-response processing
const end = process.hrtime.bigint();
console.log(`Request to ${ctx.url} executed in ${Number(end - start) / 1e6}ms`);
});Schema Validation
Kazuma integrates schema validation directly into the routing layer. Compilation occurs strictly during the application boot phase, ensuring optimal runtime execution. If a payload violates the schema, Kazuma automatically intercepts the request, blocks execution of the handler, and responds with a 400 Bad Request.
const userSchema = {
type: 'object',
properties: {
username: { type: 'string', minLength: 3 },
age: { type: 'integer', minimum: 18 }
},
required: ['username', 'age']
};
app.post('/api/users', {
schema: userSchema,
handler: (ctx) => {
// ctx.body is strictly guaranteed to match the userSchema definition
ctx.status(201).json({ created: ctx.body.username });
}
});Global Error Handling
Intercept all synchronous and asynchronous errors centrally. This mechanism prevents fatal server crashes and ensures API error responses remain uniformly formatted regardless of where the failure occurred.
app.setErrorHandler((error, ctx) => {
// Log the critical error to an external observability platform
console.error('Captured Error:', error.message);
// Transmit a sanitized error format to the client
ctx.status(500).json({
success: false,
message: 'An internal server error occurred.',
trace: error.message
});
});Dependency Injection & State Management
Inject global dependencies, such as persistent database connections or caching layers, directly into the core application instance. These dependencies become uniformly accessible across all segmented routes.
// Injecting a database connection globally
app.decorate('db', myDatabaseConnection);
app.use(async (ctx, next) => {
// Storing request-scoped authorization data
ctx.state.user = await ctx.app.decorators.db.query('SELECT current_user');
await next();
});
app.get('/profile', (ctx) => {
ctx.json({ currentUser: ctx.state.user });
});Modular Routing (Kazuma Router)
For enterprise-scale applications requiring separation of concerns, utilize the KazumaRouter to encapsulate related API endpoints into dedicated modules.
// File: users.routes.js
import { KazumaRouter } from 'kazuma-fast';
export default function(app) {
const router = new KazumaRouter(app);
router.get('/', (ctx) => ctx.json({ message: 'User list retrieved.' }));
router.post('/', (ctx) => ctx.json({ message: 'User created.' }));
return router;
}
// File: app.js
import Kazuma from 'kazuma-fast';
import userRoutes from './users.routes.js';
const app = new Kazuma();
// Mount the router under the specified URL prefix
app.mount('/users', userRoutes(app));Performance Benchmarks
In standardized local environment tests utilizing 100 concurrent connections over a sustained duration, Kazuma consistently demonstrates significant performance superiority over traditional Node.js frameworks:
- Kazuma (Hyper-Express): ~10,742 Req/Sec
- Fastify: ~7,953 Req/Sec
- Koa: ~6,914 Req/Sec
- Express: ~2,360 Req/Sec
Note: Benchmarks reflect single-core performance on standard environments. Linux-based deployments utilizing proper thread-pool allocation and PM2 clustering yield exponentially higher throughput, easily exceeding 100,000+ RPS.
