Architecture

Understanding Azu's architecture is key to building effective applications. This guide covers the core architectural patterns, request lifecycle, and design principles that make Azu powerful and type-safe.

Core Architecture Principles

Type Safety First

Azu is built around Crystal's powerful type system, providing compile-time guarantees for:

  • Request Validation: All incoming data is validated at compile time

  • Response Structure: Response objects are type-safe and consistent

  • Route Parameters: URL parameters are typed and validated

  • WebSocket Messages: Real-time communication is type-safe

Component-Based Design

Azu follows a modular, component-based architecture:

  • Endpoints: Self-contained request handlers

  • Request Contracts: Type-safe input validation

  • Response Objects: Structured output handling

  • Channels: Real-time communication handlers

  • Components: Reusable UI components

Performance by Design

Built for high performance:

  • Compile-time Optimization: Crystal's compiler optimizes your code

  • Memory Efficiency: Predictable memory usage with no GC pauses

  • Concurrent Processing: Handle thousands of connections efficiently

  • Minimal Overhead: Framework adds minimal runtime cost

Request-Response Lifecycle

1. Request Processing

When a request arrives:

  1. HTTP Server: Crystal's built-in HTTP server receives the request

  2. Middleware Chain: Request passes through configured middleware

  3. Router: Routes the request to the appropriate endpoint

  4. Endpoint: Type-safe endpoint processes the request

2. Request Validation

Request contracts automatically:

  • Parse and validate incoming data

  • Provide type-safe access to parameters

  • Generate detailed error messages

  • Ensure data integrity

3. Business Logic

4. Response Generation

Middleware Architecture

Azu uses a middleware chain pattern for request processing:

Built-in Middleware

  • RequestId: Adds unique request identifiers

  • Logger: Request/response logging

  • CORS: Cross-origin resource sharing

  • Static: Static file serving

  • Rescuer: Error handling and recovery

Custom Middleware

Routing System

Azu uses a high-performance routing tree based on Radix:

Route Features

  • HTTP Methods: Support for all standard HTTP methods

  • Path Parameters: Typed URL parameters (:id, :slug)

  • Route Groups: Organize related routes

  • Nested Routes: Hierarchical route organization

  • Route Constraints: Additional validation rules

WebSocket Architecture

Real-time communication in Azu:

Channel Pattern

Component System

Live components for interactive UI:

Component Lifecycle

  1. Mount: Component is created and registered

  2. Render: Initial HTML is generated

  3. Event Handling: Client events are processed

  4. Update: Component state changes trigger re-renders

  5. Unmount: Component is cleaned up

Template System

Azu includes a powerful template engine based on Jinja2:

Template Features

  • Variable Interpolation: {{ variable }}

  • Control Structures: {% if %} loops and conditionals

  • Template Inheritance: Extend base templates

  • Hot Reload: Automatic template reloading in development

  • Markup DSL: Programmatic HTML generation

Template Rendering

Configuration System

Centralized configuration with environment support:

Error Handling

Comprehensive error handling system:

Error Types

  • ValidationError: Request validation failures

  • NotFound: Resource not found (404)

  • Unauthorized: Authentication failures (401)

  • Forbidden: Authorization failures (403)

  • InternalServerError: Server errors (500)

Error Response Format

Performance Characteristics

Compile-time Optimizations

  • Type Elimination: Unused code is eliminated at compile time

  • Method Inlining: Small methods are inlined for performance

  • Dead Code Elimination: Unreachable code is removed

  • Constant Folding: Compile-time constant evaluation

Runtime Performance

  • Zero-cost Abstractions: Framework abstractions have minimal overhead

  • Memory Efficiency: Predictable memory usage patterns

  • Concurrent Processing: Efficient handling of multiple requests

  • Connection Pooling: Optimized database and external service connections

Benchmarking

Azu is designed for high performance:

  • Request Throughput: Handle thousands of requests per second

  • Memory Usage: Low memory footprint with predictable patterns

  • Latency: Sub-millisecond request processing overhead

  • Scalability: Efficient resource usage for horizontal scaling

Security Architecture

Built-in Security Features

  • CSRF Protection: Cross-site request forgery prevention

  • Input Validation: Comprehensive request validation

  • XSS Prevention: Automatic output escaping

  • SQL Injection Prevention: Type-safe database queries

  • Secure Headers: Security-focused HTTP headers

Security Best Practices

  • Input Sanitization: All user input is validated and sanitized

  • Output Encoding: Automatic HTML/XML encoding

  • Authentication: Secure session management

  • Authorization: Role-based access control

  • HTTPS Enforcement: Secure communication protocols

Development vs Production

Development Mode

  • Hot Reload: Automatic code and template reloading

  • Debug Logging: Detailed request/response logging

  • Error Pages: Comprehensive error information

  • Performance Monitoring: Development-time metrics

Production Mode

  • Optimized Compilation: Release-mode optimizations

  • Minimal Logging: Production-appropriate logging levels

  • Error Handling: User-friendly error responses

  • Performance Monitoring: Production metrics and alerting

Next Steps

Now that you understand Azu's architecture:

  1. Endpoints - Learn about endpoint patterns and best practices

  2. Request Contracts - Master request validation and type safety

  3. Response Objects - Structure your API responses

  4. Routing - Organize your application routes

  5. Middleware - Customize request processing

  6. WebSocket Channels - Build real-time features

  7. Components - Create interactive UI components


Understanding Azu's architecture gives you the foundation to build robust, type-safe, and performant web applications with confidence.

Last updated

Was this helpful?