PJS - Priority JSON Streaming Protocol
ð 6.3x faster than serde_json | ðŊ 5.3x faster progressive loading | ðū Bounded memory usage | ðïļ Production Ready
New in v0.3.0: Production-ready code quality with zero clippy warnings, Clean Architecture compliance, and comprehensive test coverage (196 tests). Now requires nightly Rust for zero-cost abstractions.
ð Key Features
⥠Blazing Fast
- 6.3x faster than serde_json
- 1.71 GiB/s throughput
- SIMD-accelerated parsing
ðŊ Smart Streaming
- Skeleton-first delivery
- Priority-based transmission
- Progressive enhancement
ðū Memory Efficient
- 5.3x faster progressive loading
- Bounded memory usage
- Zero-copy operations
ð§ Production Ready
- All tests passing
- Clean Architecture
ð Schema Aware
- Automatic compression
- Semantic analysis
- Type optimization
ð Developer Friendly
- Simple API
- Drop-in replacement
- Extensive documentation
ðŊ The Problem
Modern web applications face a fundamental challenge: large JSON responses block UI rendering.
Current State
- ð Analytics dashboard loads 5MB of JSON
- âąïļ User waits 2-3 seconds seeing nothing
- ðĪ User thinks app is broken and refreshes
- ð The cycle repeats
Why existing solutions fall short
Solution | Problem |
---|---|
Pagination | Requires multiple round-trips, complex state management |
GraphQL | Still sends complete response, just smaller |
JSON streaming | No semantic understanding, can't prioritize |
Compression | Reduces size but not time-to-first-byte |
âĻ The Solution: PJS
PJS revolutionizes JSON transmission by understanding your data semantically and prioritizing what matters.
Core Innovation: Semantic Prioritization
Real-World Impact
Traditional JSON Loading:
[ââââââââââââââââââââ] 100% - 2000ms - Full UI renders
PJS Loading:
[ââââââââââââââââââââ] 10% - 10ms - Critical UI visible
[ââââââââââââââââââââ] 30% - 50ms - Interactive UI
[ââââââââââââââââââââ] 100% - 2000ms - Full data loaded
User Experience: ⥠Instant â ð Happy
Key Features
ð Complete HTTP Server Integration
Production-ready Axum integration with full REST API, session management, and real-time streaming.
ðŊ Advanced Streaming Implementations
- AdaptiveFrameStream: Client capability-based optimization
- BatchFrameStream: High-throughput batch processing
- PriorityFrameStream: Priority-based frame ordering with buffering
ðïļ Domain-Driven Design Architecture
Clean architecture with CQRS pattern, event sourcing, and ports & adapters for maximum testability and maintainability.
ð Production-Ready Infrastructure
- Thread-safe in-memory storage and metrics collection
- Event publishing with subscription support
- Prometheus metrics integration
- Comprehensive middleware stack (CORS, security, compression)
ð Multiple Response Formats
Automatic format detection supporting JSON, NDJSON, and Server-Sent Events based on client Accept headers.
⥠SIMD-Accelerated Parsing
Powered by sonic-rs
for blazing fast JSON processing with zero-copy operations.
ð Real-Time WebSocket Streaming
Complete WebSocket implementation with priority-based frame delivery:
- Session Management: Track active WebSocket connections with metrics
- Priority-Based Delivery: Critical data sent first with adaptive delays
- Schema-Based Compression: Intelligent compression using multiple strategies
- Progressive Enhancement: Skeleton-first streaming with incremental updates
- Demo Servers: Interactive demonstrations of real-time streaming capabilities
ð What's New in v0.3.0
ð ïļ Production-Ready Code Quality
- Zero Clippy Warnings: All 44+ clippy warnings resolved across entire codebase
- Modern Format Strings: Updated to
format!("{var}")
syntax throughout - Enhanced Error Handling: Proper Result patterns and async trait compatibility
- Memory Safety: Fixed await-holding lock patterns and buffer alignment issues
- 196 Tests Passing: Complete test suite with all features enabled
ðïļ Clean Architecture Enforcement
- Domain Layer Isolation: Custom
JsonData
value object replacingserde_json::Value
- Type Safety: Eliminated all architecture violations in domain layer
- Seamless Conversion:
From
trait implementations forJsonData â serde_json::Value
- Proper Boundaries: Clear separation between domain and infrastructure errors
ð HTTP/WebSocket Modernization
- Axum v0.8 Compatibility: Updated route syntax from
:param
to{param}
format - StreamExt Integration: Fixed async stream processing with proper trait imports
- Body Type Updates: Modern HTTP body handling for latest axum/hyper versions
- All Tests Passing: Complete HTTP integration test suite validation
ð§ Technical Debt Resolution
- Architecture Compliance: Resolved all Clean Architecture violations
- Lint Standards: Zero warnings with strict linting enabled (
-D warnings
) - Async Patterns: Fixed await-across-locks and other async safety issues
- Type System: Enhanced type safety with better generic bounds and aliases
Benchmarks
ð Actual Performance Results
Metric | serde_json | sonic-rs | PJS | PJS Advantage |
---|---|---|---|---|
Small JSON (43B) | 275ns | 129ns | 312ns | Competitive |
Medium JSON (351B) | 1,662ns | 434ns | 590ns | 2.8x vs serde |
Large JSON (357KB) | 1,294Ξs | 216Ξs | 204Ξs | 6.3x vs serde, 1.06x vs sonic |
Memory Efficiency | Baseline | Fast | 5.3x faster progressive | Bounded memory |
Progressive Loading | Batch-only | Batch-only | 37Ξs vs 198Ξs | 5.3x faster |
ðŊ Key Performance Achievements
- 6.3x faster than serde_json for large JSON processing
- 1.06x faster than sonic-rs (SIMD library) on large datasets
- 5.3x faster progressive loading vs traditional batch processing
- 1.71 GiB/s sustained throughput (exceeding sonic-rs 1.61 GiB/s)
Installation
Add PJS to your Cargo.toml
:
[]
= "0.3.0"
# Optional: for HTTP server integration
= "0.8"
= { = "1", = ["full"] }
Or use cargo:
Quick Start
HTTP Server with Axum Integration
use Arc;
use ;
async
JavaScript/TypeScript Client Library
Use the official PJS client library for seamless integration:
HTTP Streaming
import { PjsClient, createHttpTransport } from '@pjs/client';
// Create client with HTTP transport
const client = new PjsClient({
transport: createHttpTransport({
baseUrl: 'http://localhost:3000',
format: 'sse' // or 'json', 'ndjson'
})
});
// Stream data with priority-based delivery
await client.stream({
data: {
users: [/* large array */],
dashboard: { /* complex object */ }
},
onFrame: (frame) => {
// Frames arrive in priority order
if (frame.priority >= 90) {
updateUI(frame.data); // Critical data first
}
}
});
WebSocket Real-Time Streaming
import { PjsClient, createWebSocketTransport } from '@pjs/client';
const client = new PjsClient({
transport: createWebSocketTransport({
url: 'ws://localhost:3001/ws'
})
});
// Real-time streaming with priority handling
await client.connect();
client.onFrame((frame) => {
console.log(`Priority ${frame.priority}:`, frame.data);
// Handle based on priority
switch (frame.priority) {
case 'critical':
showImmediate(frame.data);
break;
case 'high':
queueForNextFrame(frame.data);
break;
default:
processInBackground(frame.data);
}
});
WebSocket Streaming
use ;
use ;
use ;
async
Demo Servers
Start the interactive demos to see PJS in action:
# WebSocket streaming server with priority-based delivery
# Interactive demo with HTML interface and real-time visualization
# Simple demo server with basic streaming
# Performance comparison demo (PJS vs traditional JSON)
Or run root-level examples:
# Complete Axum HTTP server
# Advanced streaming demo server
# Simple usage patterns
Then visit http://127.0.0.1:3000
to see priority-based streaming in action.
Use Cases
Perfect for:
- ð Real-time dashboards - Show key metrics instantly
- ðą Mobile apps - Optimize for slow networks
- ðïļ E-commerce - Load product essentials first
- ð Financial platforms - Prioritize critical trading data
- ðŪ Gaming leaderboards - Show player's rank immediately
Architecture
PJS implements a clean, layered architecture following Domain-Driven Design principles:
1. Domain Layer
Core business logic with value objects (Priority, SessionId, JsonPath) and aggregates (StreamSession) ensuring data consistency.
2. Application Layer
CQRS pattern with separate Command and Query handlers, plus high-level services (SessionService, StreamingService) orchestrating workflows.
3. Infrastructure Layer
Adapters implementing domain ports:
- Storage: In-memory repositories with thread-safe concurrent access
- Events: Publisher/subscriber pattern for domain event distribution
- Metrics: Performance monitoring with Prometheus integration
- HTTP: Complete Axum server with middleware stack
4. Transport Abstraction
Multi-format streaming support:
- JSON: Standard response format
- NDJSON: Newline-delimited for efficient processing
- Server-Sent Events: Real-time browser compatibility
- Automatic format detection via Accept headers
5. Advanced Streaming
Intelligent frame processing:
- Priority-based delivery: Critical data first
- Adaptive buffering: Dynamic sizing based on client performance
- Batch processing: High-throughput chunk aggregation
Technical Architecture
pjs/
âââ crates/
â âââ pjs-core/ # Core protocol, domain logic, and HTTP integration
â â âââ src/
â â â âââ application/ # CQRS handlers, services, DTOs
â â â âââ domain/ # Value objects, entities, aggregates
â â â âââ infrastructure/ # HTTP, WebSocket, repositories, adapters
â â â âââ parser/ # SIMD, zero-copy, buffer pools
â â â âââ stream/ # Priority streaming, reconstruction
â â â âââ compression/ # Schema-based compression
â â âââ examples/ # Standalone demos (zero-copy, compression)
â â âââ tests/ # Integration tests
â âââ pjs-demo/ # Interactive demo servers with WebSocket streaming
â â âââ src/
â â âââ servers/ # Demo server implementations
â â âââ clients/ # WebSocket client demos
â â âââ data/ # Sample data generators (analytics, ecommerce)
â â âââ static/ # HTML interfaces
â âââ pjs-js-client/ # JavaScript/TypeScript client library â
IMPLEMENTED
â â âââ src/ # TypeScript source code with transport layers
â â âââ tests/ # Jest test suite with full coverage
â â âââ package.json # NPM configuration and dependencies
â âââ pjs-bench/ # Benchmarking suite
â âââ benches/ # Criterion.rs performance benchmarks
âââ examples/ # Root-level usage examples
âââ axum_server.rs # Complete HTTP server demo
âââ simple_usage.rs # Basic usage patterns
âââ streaming_demo_server.rs # Advanced streaming demo
Current Implementation Status
- Phase 1: â Core foundation (100% complete)
- Phase 2: â Protocol layer (100% complete)
- Phase 3: â Client/Server framework (100% complete)
- Phase 4: â Transport layer (100% complete)
- Phase 5: â Production features (100% complete)
- Phase 6: â Real-Time Streaming (100% complete)
- Phase 7: â JavaScript/TypeScript Client SDK (100% complete)
- Phase 8: â Code Quality & Production Readiness (100% complete)
- Overall: ~98% of core functionality implemented
Implemented Components
- â pjs-core: Complete Rust implementation with Clean Architecture
- â pjs-demo: Interactive demo servers with real-time WebSocket streaming
- â pjs-js-client: Full TypeScript/JavaScript client library with transport layers
- â pjs-bench: Comprehensive benchmarking suite with performance validation
- â Examples: Multiple working examples from simple to advanced usage
API Examples
HTTP Endpoints
The server provides a complete REST API:
# Create a new session
{
}
# Response: { "session_id": "sess_abc123", "expires_at": "..." }
# Get session info
# Start streaming data
{
}
# Stream frames (JSON format)
&priority=80
# Real-time Server-Sent Events
# System health check
# Response: { "status": "healthy", "version": "0.3.0" }
Working Example
A complete working server is available at examples/axum_server.rs
. To run it:
# Start the server
# Test endpoints
# Check health
# View metrics
Performance Goals
- Throughput: >4 GB/s with sonic-rs
- Time to First Byte: <10ms for critical data
- Memory Efficiency: 5-10x reduction vs traditional parsing
- CPU Utilization: Full SIMD acceleration
Building
Prerequisites
- Rust nightly (required for
impl Trait
in associated types) - CPU with AVX2 support (recommended for SIMD acceleration)
Setting up Rust Nightly
# Install nightly Rust
# Set nightly for this project
# Or use nightly globally
Quick Start
# Clone repository
# Ensure nightly Rust is active
# Build with optimizations
# Run tests
# Run the complete HTTP server example
# Build with optional features
Feature Flags
http-client
: Enable HTTP-based event publishingprometheus-metrics
: Enable Prometheus metrics collectionsimd-auto
: Auto-detect best SIMD support (default)compression
: Enable compression middleware
Framework Integration
Universal Integration Layer with Zero-Cost Abstractions
PJS provides true zero-cost abstractions using nightly Rust features for maximum performance. The Universal Framework Integration Layer uses Generic Associated Types (GATs) with impl Trait
to eliminate all runtime overhead:
use StreamingAdapter;
use Future;
// Zero-cost framework integration with GATs
Performance Benefits of Nightly Rust
Zero-Cost Abstractions:
- 1.82x faster trait dispatch vs async_trait
- Zero heap allocations for futures
- Pure stack allocation - no runtime overhead
- Static dispatch eliminates vtables
- Complete inlining for hot paths
Currently Supported
- â Axum: Full native integration with zero-cost GAT futures
- ð§ Any Framework: Universal adapter with true zero-cost abstractions
- ð Planned: Helper macros for popular frameworks (Actix, Warp, Tide)
Integration Examples
// Axum (native support)
use create_pjs_router;
let app = create_pjs_router.with_state;
// Custom framework integration
use UniversalAdapter;
let adapter = new
.with_serializer
.with_transport;
Production Features
Middleware Stack
The HTTP server includes production-ready middleware:
use *;
let app = create_pjs_router
.layer
.layer
.layer
.layer
.with_state;
Monitoring & Metrics
Built-in Prometheus metrics support:
// Automatically tracks:
// - pjs_active_sessions
// - pjs_total_sessions_created
// - pjs_frames_processed_total
// - pjs_bytes_streamed_total
// - pjs_frame_processing_time_ms
let metrics = collector.export_prometheus;
// Expose at /metrics endpoint for Prometheus scraping
Event System
Comprehensive domain event tracking:
// Events automatically generated:
// - SessionCreated, SessionActivated, SessionEnded
// - StreamStarted, StreamCompleted, FrameGenerated
// - PriorityAdjusted, ErrorOccurred
publisher.subscribe;
Contributing
We welcome contributions! See CONTRIBUTING.md for guidelines.
Development Setup
# Install development tools
# Run checks
# Run all tests
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.
Getting Started Right Now
Want to try PJS immediately? Here's the fastest way:
# Clone and run
# Set nightly Rust (required)
# Run the server
# In another terminal, test the API
# Try Server-Sent Events streaming
Running Performance Benchmarks
To verify the performance claims, run the comprehensive benchmark suite:
# Run all benchmarks
# Or run specific benchmarks:
Results show PJS 6.3x faster than serde_json and 1.06x faster than sonic-rs on large JSON.
The server will show:
- ð Server starting message
- ð Health check endpoint
- ð Available API endpoints
- ðŊ Demo data streaming capabilities
Roadmap
Next Steps
- Connection lifecycle management â
- WebSocket real-time streaming â
- Performance benchmarks vs alternatives â
- JavaScript/TypeScript client library â
- Universal framework integration layer
- Schema validation engine
- Custom priority strategies
Acknowledgments
Built with:
- sonic-rs - Lightning fast SIMD JSON parser
- axum - Ergonomic web framework for Rust
- tokio - Async runtime for Rust
- bytes - Efficient byte buffer management
Community
- ð Documentation - Complete protocol specification
- ð Changelog - Detailed version history
- ð Benchmarks - Comprehensive performance results
- ðŽ Discussions - Questions and ideas
PJS: Because users shouldn't wait for data they don't need yet.