Documentation Index Fetch the complete documentation index at: https://ksync.klastra.ai/llms.txt
Use this file to discover all available pages before exploring further.
Overview
This section provides practical examples demonstrating how to use kSync in real-world applications. Each example includes complete, runnable code with explanations.
Chat Application Real-time chat with typing indicators and presence
Todo Sync Collaborative todo list with offline support
AI Streaming AI chat with streaming responses and presence
Multiplayer Game Real-time multiplayer game with 100+ players
Running Examples
All examples are included in the kSync repository and can be run locally:
Prerequisites
# Clone the repository
git clone https://github.com/klastra-ai/ksync.git
cd ksync
# Install dependencies
bun install
Basic Examples
Chat App
Sync Demo
AI Streaming
# Terminal 1: Start the server
bun run server/websocket-server.ts
# Terminal 2: Run the chat example
bun run examples/basic.ts
# Terminal 1: Start the server
bun run server/websocket-server.ts
# Terminal 2: Run the sync example
bun run examples/sync.ts
# Terminal 1: Start the server
bun run examples/nextjs-game/server.ts
# Terminal 2: Run the streaming example
bun run examples/streaming.ts
Next.js Game Example
# Terminal 1: Start the game server
cd examples/nextjs-game
bun run server.ts
# Terminal 2: Start the Next.js app
bun run dev
# Open http://localhost:3000 in multiple tabs
Example Categories
🚀 Getting Started
Perfect for beginners learning kSync fundamentals:
Basic Chat : Simple message sending and receiving
Schema Validation : Type-safe event handling
Local Storage : Offline-first development
Event Listeners : Reactive UI updates
🔄 Real-Time Sync
Examples demonstrating multi-client synchronization:
Todo Sync : Collaborative task management
Presence Tracking : User online/offline status
Conflict Resolution : Handling concurrent edits
Connection Management : Reconnection and error handling
🤖 AI Integration
AI-powered applications with streaming:
Streaming Chat : Word-by-word AI responses
Presence Updates : Real-time typing indicators
Error Handling : Graceful failure management
Performance : Efficient streaming protocols
🎮 Advanced Use Cases
Complex applications showcasing kSync’s capabilities:
Multiplayer Games : 100+ concurrent players
Real-Time Collaboration : Document editing
IoT Dashboards : Sensor data streaming
Financial Trading : Real-time price updates
Code Structure
Each example follows a consistent structure:
examples/
├── basic.ts # Simple chat application
├── sync.ts # Multi-client synchronization
├── streaming.ts # AI streaming example
├── nextjs-game/ # Complete Next.js application
│ ├── server.ts # Game server
│ ├── app/page.tsx # React components
│ └── lib/ksync-client.ts # Client configuration
└── README.md # Examples overview
Example Template
Each example includes:
Schema Definitions : Zod schemas for type safety
Event Handlers : Reactive event processing
State Management : Materializers for UI state
Error Handling : Graceful error recovery
Performance : Optimizations and best practices
Interactive Demos
Try these examples in your browser:
Live Chat Demo Real-time chat application with multiple users
Todo Sync Demo Collaborative todo list with offline support
Game Demo Multiplayer game with real-time movement
AI Chat Demo AI chat with streaming responses
Learning Path
Follow this recommended learning path:
1. Start with Basics
// examples/basic.ts
import { z } from 'zod' ;
import { createKSync } from '@klastra/ksync' ;
const ksync = createKSync ();
// Define schema
ksync . defineSchema ( 'message' , z . object ({
content: z . string (),
author: z . string (),
}));
// Listen for events
ksync . on ( 'message' , ( event ) => {
console . log ( ` ${ event . data . author } : ${ event . data . content } ` );
});
// Send events
await ksync . send ( 'message' , {
content: 'Hello, world!' ,
author: 'Alice' ,
});
2. Add Real-Time Sync
// Enable real-time synchronization
const ksync = createKSync ({
serverUrl: 'ws://localhost:8080' ,
debug: true ,
});
await ksync . initialize ();
3. Implement State Management
// Define materializers for UI state
ksync . defineMaterializer ( 'messages' , ( events ) => {
return events
. filter ( e => e . type === 'message' )
. map ( e => e . data )
. sort (( a , b ) => a . timestamp - b . timestamp );
});
// Get current state
const messages = ksync . getState ( 'messages' );
4. Add Advanced Features
// Streaming support
const streamId = await ksync . startStream ( 'ai-response' , {
prompt: 'Tell me a story' ,
model: 'gpt-4' ,
});
// Presence tracking
ksync . updatePresence ({
status: 'online' ,
currentPage: '/chat' ,
});
Common Patterns
Event-Driven Architecture
// Command events (user actions)
await ksync . send ( 'user-join-channel' , { userId , channelId });
await ksync . send ( 'message-send' , { content , channelId });
await ksync . send ( 'user-leave-channel' , { userId , channelId });
// State events (system responses)
await ksync . send ( 'channel-updated' , { channelId , memberCount });
await ksync . send ( 'message-delivered' , { messageId , timestamp });
Optimistic Updates
// Update UI immediately
addMessageToUI ( messageData );
// Send event (may fail)
try {
await ksync . send ( 'message' , messageData );
} catch ( error ) {
// Revert UI on failure
removeMessageFromUI ( messageData . id );
showError ( 'Failed to send message' );
}
Offline Support
// Events are queued when offline
await ksync . send ( 'message' , data ); // Works offline
// Sync when connection returns
ksync . on ( 'sync-complete' , () => {
console . log ( 'All offline events synced!' );
});
Event Batching
// Events are automatically batched
const promises = users . map ( user =>
ksync . send ( 'user-joined' , { userId: user . id })
);
await Promise . all ( promises ); // Sent as single batch
Memory Management
// Configure automatic cleanup
const ksync = createKSync ({
storage: new IndexedDBStorage ({
maxEvents: 10000 ,
maxAge: 7 * 24 * 60 * 60 * 1000 , // 7 days
})
});
Connection Efficiency
// Only one connection per origin
// Multiple tabs share the same connection
// Automatic reconnection on network issues
Troubleshooting
Common Issues
Check that the server is running and accessible: # Test WebSocket connection
curl -i -N -H "Connection: Upgrade" \
-H "Upgrade: websocket" \
-H "Sec-WebSocket-Key: test" \
-H "Sec-WebSocket-Version: 13" \
http://localhost:8080/
Ensure your event data matches the schema: try {
await ksync . send ( 'message' , data );
} catch ( error ) {
if ( error instanceof z . ZodError ) {
console . error ( 'Validation errors:' , error . errors );
}
}
Remove event listeners when components unmount: useEffect (() => {
const handler = ( event ) => { /* ... */ };
ksync . on ( 'message' , handler );
return () => {
ksync . off ( 'message' , handler );
};
}, []);
Next Steps
Chat Application Build a real-time chat application
Todo Sync Create a collaborative todo list
AI Streaming Implement AI chat with streaming
Multiplayer Game Build a real-time multiplayer game