|
| 1 | +#!/usr/bin/env bun |
| 2 | + |
| 3 | +import { CompressionTypes, Kafka } from 'kafkajs'; |
| 4 | +import { randomUUID } from 'node:crypto'; |
| 5 | + |
| 6 | +const BROKER = process.env.KAFKA_BROKERS || 'localhost:9092'; |
| 7 | +const TEST_TOPIC = process.env.KAFKA_TEST_TOPIC || 'stress-test-events'; |
| 8 | + |
| 9 | +// CLI arguments |
| 10 | +const args = process.argv.slice(2); |
| 11 | +const config = { |
| 12 | + messagesPerSecond: Number.parseInt(args[0]) || 10000, |
| 13 | + durationSeconds: Number.parseInt(args[1]) || 10, |
| 14 | + batchSize: Number.parseInt(args[2]) || 500, |
| 15 | + numProducers: Number.parseInt(args[3]) || 1, |
| 16 | +}; |
| 17 | + |
| 18 | +console.log('🔧 Configuration:'); |
| 19 | +console.log(` Broker: ${BROKER}`); |
| 20 | +console.log(` Topic: ${TEST_TOPIC}`); |
| 21 | +console.log(` Messages/sec: ${config.messagesPerSecond}`); |
| 22 | +console.log(` Duration: ${config.durationSeconds}s`); |
| 23 | +console.log(` Batch size: ${config.batchSize}`); |
| 24 | +console.log(` Concurrent producers: ${config.numProducers}`); |
| 25 | +console.log(''); |
| 26 | + |
| 27 | +/** |
| 28 | + * Generate a realistic analytics event payload |
| 29 | + */ |
| 30 | +const generateEvent = (index: number) => { |
| 31 | + const eventId = randomUUID(); |
| 32 | + const sessionId = randomUUID(); |
| 33 | + const anonymousId = randomUUID(); |
| 34 | + const clientId = `client-${Math.floor(Math.random() * 100)}`; |
| 35 | + |
| 36 | + return { |
| 37 | + id: randomUUID(), |
| 38 | + client_id: clientId, |
| 39 | + event_name: 'pageview', |
| 40 | + anonymous_id: anonymousId, |
| 41 | + time: Date.now(), |
| 42 | + session_id: sessionId, |
| 43 | + event_type: 'track', |
| 44 | + event_id: eventId, |
| 45 | + session_start_time: Date.now() - Math.random() * 300000, |
| 46 | + timestamp: Date.now(), |
| 47 | + referrer: 'https://google.com', |
| 48 | + url: `https://example.com/page-${index % 100}`, |
| 49 | + path: `/page-${index % 100}`, |
| 50 | + title: `Page ${index % 100}`, |
| 51 | + ip: `192.168.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`, |
| 52 | + user_agent: |
| 53 | + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', |
| 54 | + browser_name: 'Chrome', |
| 55 | + browser_version: '120.0.0', |
| 56 | + os_name: 'Windows', |
| 57 | + os_version: '10', |
| 58 | + device_type: 'desktop', |
| 59 | + device_brand: '', |
| 60 | + device_model: '', |
| 61 | + country: 'US', |
| 62 | + region: 'CA', |
| 63 | + city: 'San Francisco', |
| 64 | + screen_resolution: '1920x1080', |
| 65 | + viewport_size: '1920x1080', |
| 66 | + language: 'en-US', |
| 67 | + timezone: 'America/Los_Angeles', |
| 68 | + connection_type: '4g', |
| 69 | + rtt: 50, |
| 70 | + downlink: 10, |
| 71 | + time_on_page: Math.floor(Math.random() * 60000), |
| 72 | + scroll_depth: Math.floor(Math.random() * 100), |
| 73 | + interaction_count: Math.floor(Math.random() * 50), |
| 74 | + page_count: 1, |
| 75 | + utm_source: '', |
| 76 | + utm_medium: '', |
| 77 | + utm_campaign: '', |
| 78 | + utm_term: '', |
| 79 | + utm_content: '', |
| 80 | + load_time: Math.floor(Math.random() * 3000), |
| 81 | + dom_ready_time: Math.floor(Math.random() * 2000), |
| 82 | + dom_interactive: Math.floor(Math.random() * 1500), |
| 83 | + ttfb: Math.floor(Math.random() * 500), |
| 84 | + connection_time: Math.floor(Math.random() * 100), |
| 85 | + render_time: Math.floor(Math.random() * 1000), |
| 86 | + redirect_time: 0, |
| 87 | + domain_lookup_time: Math.floor(Math.random() * 50), |
| 88 | + properties: '{}', |
| 89 | + created_at: Date.now(), |
| 90 | + }; |
| 91 | +}; |
| 92 | + |
| 93 | +/** |
| 94 | + * Create a Kafka producer optimized for maximum throughput |
| 95 | + */ |
| 96 | +const createProducer = async () => { |
| 97 | + const kafka = new Kafka({ |
| 98 | + clientId: `basket-stress-test-${randomUUID()}`, |
| 99 | + brokers: [BROKER], |
| 100 | + }); |
| 101 | + |
| 102 | + const producer = kafka.producer({ |
| 103 | + allowAutoTopicCreation: true, |
| 104 | + maxInFlightRequests: 5, |
| 105 | + idempotent: false, |
| 106 | + }); |
| 107 | + |
| 108 | + await producer.connect(); |
| 109 | + return producer; |
| 110 | +}; |
| 111 | + |
| 112 | +/** |
| 113 | + * Send a batch of messages (fire-and-forget for maximum throughput) |
| 114 | + */ |
| 115 | +const sendBatch = (producer: any, batchSize: number, startIndex: number) => { |
| 116 | + const messages = []; |
| 117 | + for (let i = 0; i < batchSize; i++) { |
| 118 | + const event = generateEvent(startIndex + i); |
| 119 | + messages.push({ |
| 120 | + key: event.client_id, |
| 121 | + value: JSON.stringify(event), |
| 122 | + }); |
| 123 | + } |
| 124 | + |
| 125 | + return producer.send({ |
| 126 | + topic: TEST_TOPIC, |
| 127 | + messages, |
| 128 | + compression: CompressionTypes.GZIP, |
| 129 | + }); |
| 130 | +}; |
| 131 | + |
| 132 | +/** |
| 133 | + * Run stress test for a single producer (fire-and-forget for max throughput) |
| 134 | + */ |
| 135 | +const runProducerStressTest = async ( |
| 136 | + producerId: number, |
| 137 | + messagesPerProducer: number, |
| 138 | + targetMessagesPerSecond: number, |
| 139 | + durationSeconds: number |
| 140 | +) => { |
| 141 | + const producer = await createProducer(); |
| 142 | + console.log(`✅ Producer ${producerId} connected`); |
| 143 | + |
| 144 | + const batchSize = config.batchSize; |
| 145 | + const promises = []; |
| 146 | + |
| 147 | + // Fire off all batches as fast as possible (fire-and-forget) |
| 148 | + // No rate limiting - let Kafka handle the backpressure |
| 149 | + for (let i = 0; i < messagesPerProducer; i += batchSize) { |
| 150 | + const batchPromise = sendBatch(producer, batchSize, i); |
| 151 | + promises.push(batchPromise); |
| 152 | + } |
| 153 | + |
| 154 | + // Wait for all messages to be sent |
| 155 | + await Promise.all(promises); |
| 156 | + await producer.disconnect(); |
| 157 | + |
| 158 | + return messagesPerProducer; |
| 159 | +}; |
| 160 | + |
| 161 | +/** |
| 162 | + * Main stress test execution |
| 163 | + */ |
| 164 | +const runStressTest = async () => { |
| 165 | + const totalMessages = |
| 166 | + config.messagesPerSecond * config.durationSeconds * config.numProducers; |
| 167 | + const messagesPerProducer = Math.floor(totalMessages / config.numProducers); |
| 168 | + |
| 169 | + console.log('🚀 Starting Kafka/Redpanda stress test...'); |
| 170 | + console.log(`📊 Total messages: ${totalMessages.toLocaleString()}`); |
| 171 | + console.log(`📦 Messages per producer: ${messagesPerProducer.toLocaleString()}`); |
| 172 | + console.log(''); |
| 173 | + |
| 174 | + const startTime = Date.now(); |
| 175 | + |
| 176 | + // Create progress tracker |
| 177 | + const progressInterval = setInterval(() => { |
| 178 | + const elapsed = (Date.now() - startTime) / 1000; |
| 179 | + console.log(`⏱️ Elapsed time: ${elapsed.toFixed(1)}s`); |
| 180 | + }, 2000); |
| 181 | + |
| 182 | + // Run all producers concurrently |
| 183 | + const producerTasks = Array.from({ length: config.numProducers }, (_, idx) => |
| 184 | + runProducerStressTest( |
| 185 | + idx + 1, |
| 186 | + messagesPerProducer, |
| 187 | + config.messagesPerSecond, |
| 188 | + config.durationSeconds |
| 189 | + ) |
| 190 | + ); |
| 191 | + |
| 192 | + const results = await Promise.all(producerTasks); |
| 193 | + clearInterval(progressInterval); |
| 194 | + |
| 195 | + const endTime = Date.now(); |
| 196 | + const duration = (endTime - startTime) / 1000; |
| 197 | + const totalSent = results.reduce((sum, count) => sum + count, 0); |
| 198 | + const actualThroughput = Math.floor(totalSent / duration); |
| 199 | + |
| 200 | + console.log(''); |
| 201 | + console.log('📈 Results:'); |
| 202 | + console.log(` Total messages sent: ${totalSent.toLocaleString()}`); |
| 203 | + console.log(` Duration: ${duration.toFixed(2)}s`); |
| 204 | + console.log(` Throughput: ${actualThroughput.toLocaleString()} msg/sec`); |
| 205 | + console.log( |
| 206 | + ` Avg per producer: ${Math.floor(actualThroughput / config.numProducers).toLocaleString()} msg/sec` |
| 207 | + ); |
| 208 | + console.log(''); |
| 209 | + console.log('✅ Stress test completed successfully!'); |
| 210 | +}; |
| 211 | + |
| 212 | +// Handle graceful shutdown |
| 213 | +process.on('SIGINT', () => { |
| 214 | + console.log('\n⚠️ Interrupted, shutting down...'); |
| 215 | + process.exit(0); |
| 216 | +}); |
| 217 | + |
| 218 | +process.on('SIGTERM', () => { |
| 219 | + console.log('\n⚠️ Terminated, shutting down...'); |
| 220 | + process.exit(0); |
| 221 | +}); |
| 222 | + |
| 223 | +// Run the stress test |
| 224 | +runStressTest() |
| 225 | + .then(() => { |
| 226 | + process.exit(0); |
| 227 | + }) |
| 228 | + .catch((error) => { |
| 229 | + console.error('❌ Stress test failed:', error); |
| 230 | + process.exit(1); |
| 231 | + }); |
| 232 | + |
0 commit comments