@cbnsndwch/zero-sources

Troubleshooting

Solutions to common issues and problems

This guide helps you diagnose and fix common issues with Zero Sources.

MongoDB Issues

Replica Set Not Enabled

Error: MongoServerError: The $changeStream stage is only supported on replica sets

Solution: MongoDB must run in replica set mode for change streams.

# Start MongoDB with replica set
docker run -d --name mongodb \
  -p 27017:27017 \
  mongo:latest \
  --replSet rs0

# Initialize replica set
docker exec mongodb mongosh --eval "rs.initiate()"

# Verify status
docker exec mongodb mongosh --eval "rs.status()"

Connection Refused

Error: MongoNetworkError: connect ECONNREFUSED

Solution: Ensure MongoDB is running and accessible.

# Check MongoDB is running
docker ps | grep mongodb

# Test connection
mongosh mongodb://localhost:27017

Authentication Failed

Error: MongoServerError: Authentication failed

Solution: Check credentials in your .env file.

MONGODB_URI=mongodb://username:password@localhost:27017/dbname?authSource=admin

Change Source Issues

Changes Not Streaming

Problem: Database changes don't appear in clients

Checklist:

  1. Verify MongoDB replica set is enabled
  2. Check change source is running
  3. Verify WebSocket connection
  4. Check table mappings configuration
  5. Inspect change source logs

Debug:

# Enable debug logging
DEBUG=zero:* pnpm --filter source-mongodb-server start

# Test WebSocket connection
wscat -c ws://localhost:3000/changes/v0/stream

Schema Mismatch

Error: Schema validation failed

Solution: Ensure MongoDB data matches Zero schema.

// Check your schema matches MongoDB structure
const schema = createTableSchema({
    tableName: 'message',
    columns: {
        id: { type: 'string' }, // MongoDB: _id
        content: { type: 'string' } // MongoDB: content
    },
    primaryKey: ['id']
});

Field Mapping Errors

Problem: Fields are missing or have wrong values

Solution: Check table mappings configuration.

{
    "message": {
        "collection": "messages",
        "fields": {
            "id": "_id", // Zero field: MongoDB field
            "content": "body" // Map "body" to "content"
        }
    }
}

WebSocket Issues

Connection Drops

Problem: Frequent disconnections

Solutions:

  • Check network stability
  • Increase timeout settings
  • Enable WebSocket keepalive
  • Check firewall/proxy settings
// Increase timeout
const gateway = new ChangeSourceGateway({
    pingTimeout: 60000, // 60 seconds
    pingInterval: 25000 // 25 seconds
});

High Latency

Problem: Slow change propagation

Solutions:

  • Check MongoDB change stream lag
  • Monitor CPU/memory usage
  • Enable compression
  • Scale horizontally

Client Issues

Initial Load Slow

Problem: Slow first load

Solutions:

  • Implement pagination
  • Add indexes to MongoDB
  • Cache initial data
  • Use incremental loading

Memory Usage Growing

Problem: Client memory usage increases over time

Solutions:

  • Limit query results
  • Implement data expiration
  • Use virtual scrolling
  • Clear old data periodically

Performance Issues

High CPU Usage

Causes:

  • Too many change streams
  • Complex aggregations
  • Insufficient indexes

Solutions:

# Profile MongoDB
db.setProfilingLevel(2)
db.system.profile.find().sort({ts:-1}).limit(5)

# Check indexes
db.messages.getIndexes()

# Add index
db.messages.createIndex({ createdAt: -1 })

Memory Leaks

Diagnosis:

# Monitor memory
node --inspect index.js

# Chrome DevTools → Memory → Take heap snapshot

Common Causes:

  • Not closing change streams
  • Event listener leaks
  • Cached data not cleaned up

Development Issues

Build Errors

Error: TypeScript compilation errors

Solution:

# Clean build cache
pnpm clean
rm -rf node_modules .turbo

# Reinstall
pnpm install

# Rebuild
pnpm build

Hot Reload Not Working

Problem: Changes not reflected during development

Solution:

# Restart dev server
pnpm dev

# Clear Vite cache
rm -rf apps/docs/node_modules/.vite

Debugging Tools

Enable Debug Logging

# Change source debugging
DEBUG=zero:change-source pnpm start

# MongoDB debugging
DEBUG=mongodb:* pnpm start

# All debugging
DEBUG=* pnpm start

Inspect Database

// MongoDB shell
use zero_sources

// View messages
db.messages.find().limit(5)

// Watch change stream
const changeStream = db.messages.watch()
while (changeStream.hasNext()) {
  printjson(changeStream.next())
}

Test WebSocket

# Install wscat
npm install -g wscat

# Connect to gateway
wscat -c ws://localhost:3000/changes/v0/stream

# Send subscribe message
{"type":"subscribe","tables":["message"]}

Getting Help

If you're still stuck:

  1. Check Logs: Review application and MongoDB logs
  2. Search Issues: Check GitHub issues for similar problems
  3. Ask Community: Post in GitHub Discussions
  4. Create Issue: Report bugs with reproduction steps

Useful Information

When reporting issues, include:

  • Zero Sources version
  • MongoDB version
  • Node.js version
  • Operating system
  • Error messages and stack traces
  • Minimal reproduction example

Common Patterns

Graceful Shutdown

process.on('SIGTERM', async () => {
    console.log('Shutting down gracefully...');
    await changeStream.close();
    await mongoClient.close();
    process.exit(0);
});

Error Handling

changeStream.on('error', async error => {
    console.error('Change stream error:', error);

    // Reconnect after delay
    await sleep(5000);
    await restartChangeStream();
});

How was this page?