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). Ready for production deployment.
ð 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
Client Usage (HTTP/SSE)
// Create session
const sessionResponse = await ;
const = await sessionResponse.;
// Start streaming
await ;
// Receive real-time updates via Server-Sent Events
const eventSource = ;
eventSource ;
WebSocket Streaming
use ;
use ;
use ;
async
Demo Servers
Start the interactive demo to see PJS in action:
# WebSocket streaming server
# Interactive demo with HTML interface
# Simple demo server
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
â âââ pjs-demo/ # Interactive demo servers with WebSocket streaming
â â âââ servers/ # Demo server implementations
â â âââ clients/ # WebSocket client demos
â â âââ data/ # Sample data generators
â â âââ static/ # HTML interfaces
â âââ pjs-client/ # Client implementations (planned)
â âââ pjs-server/ # Server framework extensions (planned)
â âââ pjs-transport/ # Advanced transport layers (planned)
â âââ pjs-gpu/ # GPU acceleration (planned)
â âââ pjs-bench/ # Benchmarking suite (planned)
âââ examples/
âââ axum_server.rs # Complete working HTTP server 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: â Code Quality & Production Readiness (100% complete)
- Overall: ~95% of core functionality implemented
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 1.85+
- CPU with AVX2 support (recommended for SIMD acceleration)
Quick Start
# Clone repository
# 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
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
# 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
- 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.