Overview

This section provides practical examples demonstrating how to use kSync in real-world applications. Each example includes complete, runnable code with explanations.

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

# Terminal 1: Start the server
bun run server/websocket-server.ts

# Terminal 2: Run the chat example
bun run examples/basic.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:
  1. Schema Definitions: Zod schemas for type safety
  2. Event Handlers: Reactive event processing
  3. State Management: Materializers for UI state
  4. Error Handling: Graceful error recovery
  5. Performance: Optimizations and best practices

Interactive Demos

Try these examples in your browser:

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!');
});

Performance Tips

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

Next Steps