Skip to content

Reconnect Strategy

WebSocket connections can drop. Implement auto-reconnect.

Terminal window
npm install ws
import WebSocket from 'ws';
// Your filter - store it so you can resubscribe on reconnect
const filters = {
platform: ["pump_fun"],
eventType: ["create"]
};
let ws: WebSocket;
let reconnectAttempt = 0;
function connect() {
ws = new WebSocket('wss://ws.darkfibre.dev/v1?apiKey=api_your_key_here');
ws.onopen = () => {
console.log('Connected');
reconnectAttempt = 0;
// Resubscribe with same filters
ws.send(JSON.stringify({ type: 'subscribe', filters }));
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data.toString());
if (message.type === 'transaction') {
console.log('Transaction:', message.data);
}
};
ws.onclose = () => {
// Exponential backoff: 1s, 2s, 4s, 8s... max 30s
const delay = Math.min(1000 * Math.pow(2, reconnectAttempt++), 30000);
console.log(`Reconnecting in ${delay}ms...`);
setTimeout(connect, delay);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
connect();
  • Store your filters — you need to resubscribe after reconnect
  • Server is stateless — disconnect clears your subscription
  • Exponential backoff — prevents hammering the server during outages
  • No special reconnect protocol — just connect and subscribe again