Reconnect Strategy
WebSocket connections can drop. Implement auto-reconnect.
Auto-Reconnect
Section titled “Auto-Reconnect”npm install wsimport WebSocket from 'ws';
// Your filter - store it so you can resubscribe on reconnectconst 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();pip install websocket-clientimport websocketimport json
# Your filter - store it so you can resubscribe on reconnectfilters = { "platform": ["pump_fun"], "eventType": ["create"]}
def on_open(ws): print("Connected") # Resubscribe with same filters ws.send(json.dumps({"type": "subscribe", "filters": filters}))
def on_message(ws, message): data = json.loads(message) if data.get("type") == "transaction": print("Transaction:", data["data"])
def on_close(ws, close_status_code, close_msg): print("Disconnected, reconnecting...")
ws = websocket.WebSocketApp( "wss://ws.darkfibre.dev/v1?apiKey=api_your_key_here", on_open=on_open, on_message=on_message, on_close=on_close)
# Auto-reconnect with exponential backoffws.run_forever(reconnect=5) # Max reconnect delay in secondsKey Points
Section titled “Key Points”- 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