|
| 1 | +package io.runcycles.protocol.api; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.*; |
| 4 | +import org.springframework.http.ResponseEntity; |
| 5 | +import org.springframework.test.context.ActiveProfiles; |
| 6 | + |
| 7 | +import java.util.*; |
| 8 | +import java.util.concurrent.*; |
| 9 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 10 | +import java.util.concurrent.atomic.AtomicInteger; |
| 11 | + |
| 12 | +import static org.assertj.core.api.Assertions.assertThat; |
| 13 | + |
| 14 | +/** |
| 15 | + * Concurrent load benchmarks for Cycles Protocol operations. |
| 16 | + * |
| 17 | + * Measures throughput (ops/sec) and latency under concurrent load by running |
| 18 | + * multiple threads executing Reserve→Commit lifecycles simultaneously. |
| 19 | + * |
| 20 | + * Tests ramp from 8 → 16 → 32 concurrent threads to reveal contention |
| 21 | + * at the Redis connection pool (max 50), Lua script execution, and |
| 22 | + * Spring Boot request processing layers. |
| 23 | + * |
| 24 | + * Results are CI-environment sensitive — latency and throughput depend on |
| 25 | + * container resources, Redis container networking, and JVM warm-up. |
| 26 | + * |
| 27 | + * Run separately: mvn test -Pbenchmark |
| 28 | + */ |
| 29 | +@DisplayName("Concurrent Load Benchmarks") |
| 30 | +@Tag("benchmark") |
| 31 | +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) |
| 32 | +@ActiveProfiles({"test", "benchmark"}) |
| 33 | +class CyclesProtocolConcurrentBenchmarkTest extends BaseIntegrationTest { |
| 34 | + |
| 35 | + private static final int WARMUP_OPS = 50; |
| 36 | + private static final long MEASURE_DURATION_MS = 5_000; |
| 37 | + /** Max acceptable error rate (%) before failing the test */ |
| 38 | + private static final double MAX_ERROR_RATE_PERCENT = 1.0; |
| 39 | + |
| 40 | + private static final List<ConcurrencyResult> ALL_RESULTS = new ArrayList<>(); |
| 41 | + |
| 42 | + record ConcurrencyResult(int threads, long totalOps, double opsPerSec, |
| 43 | + long p50, long p95, long p99, long min, long max, int errors) {} |
| 44 | + |
| 45 | + @AfterAll |
| 46 | + static void printSummary() { |
| 47 | + if (ALL_RESULTS.isEmpty()) return; |
| 48 | + |
| 49 | + System.out.println(); |
| 50 | + System.out.println("+----------+----------+-----------+--------+--------+--------+--------+--------+--------+"); |
| 51 | + System.out.println("| Threads | Total Ops| Ops/sec | p50 | p95 | p99 | min | max | Errors |"); |
| 52 | + System.out.println("+----------+----------+-----------+--------+--------+--------+--------+--------+--------+"); |
| 53 | + for (ConcurrencyResult r : ALL_RESULTS) { |
| 54 | + System.out.printf("| %8d | %8d | %9.1f | %5.1fms| %5.1fms| %5.1fms| %5.1fms| %5.1fms| %6d |%n", |
| 55 | + r.threads, r.totalOps, r.opsPerSec, |
| 56 | + r.p50 / 1_000_000.0, r.p95 / 1_000_000.0, r.p99 / 1_000_000.0, |
| 57 | + r.min / 1_000_000.0, r.max / 1_000_000.0, r.errors); |
| 58 | + } |
| 59 | + System.out.println("+----------+----------+-----------+--------+--------+--------+--------+--------+--------+"); |
| 60 | + System.out.printf(" Duration per level: %ds (after %d warmup ops)%n", |
| 61 | + MEASURE_DURATION_MS / 1000, WARMUP_OPS); |
| 62 | + System.out.println(); |
| 63 | + } |
| 64 | + |
| 65 | + @Test |
| 66 | + @Order(1) |
| 67 | + @DisplayName("Reserve→Commit lifecycle at 8 threads") |
| 68 | + void concurrentLifecycle_8threads() throws Exception { |
| 69 | + runConcurrentLifecycle(8); |
| 70 | + } |
| 71 | + |
| 72 | + @Test |
| 73 | + @Order(2) |
| 74 | + @DisplayName("Reserve→Commit lifecycle at 16 threads") |
| 75 | + void concurrentLifecycle_16threads() throws Exception { |
| 76 | + runConcurrentLifecycle(16); |
| 77 | + } |
| 78 | + |
| 79 | + @Test |
| 80 | + @Order(3) |
| 81 | + @DisplayName("Reserve→Commit lifecycle at 32 threads") |
| 82 | + void concurrentLifecycle_32threads() throws Exception { |
| 83 | + runConcurrentLifecycle(32); |
| 84 | + } |
| 85 | + |
| 86 | + private void runConcurrentLifecycle(int threadCount) throws Exception { |
| 87 | + // Re-seed budget with enough headroom for sustained concurrent load |
| 88 | + try (var jedis = jedisPool.getResource()) { |
| 89 | + seedBudget(jedis, TENANT_A, "TOKENS", 1_000_000_000L); |
| 90 | + } |
| 91 | + |
| 92 | + // Warm up: sequential operations to prime JIT, connection pool, EVALSHA cache |
| 93 | + for (int i = 0; i < WARMUP_OPS; i++) { |
| 94 | + String resId = createReservationAndGetId(TENANT_A, API_KEY_SECRET_A, 100); |
| 95 | + post("/v1/reservations/" + resId + "/commit", API_KEY_SECRET_A, commitBody(80)); |
| 96 | + } |
| 97 | + |
| 98 | + ExecutorService executor = Executors.newFixedThreadPool(threadCount); |
| 99 | + try { |
| 100 | + ConcurrentLinkedQueue<Long> timings = new ConcurrentLinkedQueue<>(); |
| 101 | + AtomicInteger errorCount = new AtomicInteger(0); |
| 102 | + CountDownLatch startLatch = new CountDownLatch(1); |
| 103 | + AtomicBoolean running = new AtomicBoolean(true); |
| 104 | + |
| 105 | + // Submit worker tasks |
| 106 | + for (int t = 0; t < threadCount; t++) { |
| 107 | + executor.submit(() -> { |
| 108 | + try { |
| 109 | + startLatch.await(); |
| 110 | + } catch (InterruptedException e) { |
| 111 | + Thread.currentThread().interrupt(); |
| 112 | + return; |
| 113 | + } |
| 114 | + |
| 115 | + while (running.get()) { |
| 116 | + long start = System.nanoTime(); |
| 117 | + try { |
| 118 | + Map<String, Object> reserveBody = reservationBody(TENANT_A, 100); |
| 119 | + ResponseEntity<Map> reserveResp = post("/v1/reservations", API_KEY_SECRET_A, reserveBody); |
| 120 | + if (!reserveResp.getStatusCode().is2xxSuccessful()) { |
| 121 | + errorCount.incrementAndGet(); |
| 122 | + continue; |
| 123 | + } |
| 124 | + String resId = (String) reserveResp.getBody().get("reservation_id"); |
| 125 | + |
| 126 | + ResponseEntity<Map> commitResp = post("/v1/reservations/" + resId + "/commit", |
| 127 | + API_KEY_SECRET_A, commitBody(80)); |
| 128 | + if (!commitResp.getStatusCode().is2xxSuccessful()) { |
| 129 | + errorCount.incrementAndGet(); |
| 130 | + continue; |
| 131 | + } |
| 132 | + |
| 133 | + timings.add(System.nanoTime() - start); |
| 134 | + } catch (Exception e) { |
| 135 | + errorCount.incrementAndGet(); |
| 136 | + } |
| 137 | + } |
| 138 | + }); |
| 139 | + } |
| 140 | + |
| 141 | + // Release all threads and measure for MEASURE_DURATION_MS |
| 142 | + startLatch.countDown(); |
| 143 | + Thread.sleep(MEASURE_DURATION_MS); |
| 144 | + running.set(false); |
| 145 | + |
| 146 | + // Wait for in-flight operations to complete |
| 147 | + executor.shutdown(); |
| 148 | + if (!executor.awaitTermination(30, TimeUnit.SECONDS)) { |
| 149 | + executor.shutdownNow(); |
| 150 | + } |
| 151 | + |
| 152 | + // Collect and analyze results |
| 153 | + long[] sorted = timings.stream().mapToLong(Long::longValue).sorted().toArray(); |
| 154 | + int totalOps = sorted.length; |
| 155 | + int errors = errorCount.get(); |
| 156 | + double opsPerSec = totalOps / (MEASURE_DURATION_MS / 1000.0); |
| 157 | + |
| 158 | + ConcurrencyResult result; |
| 159 | + if (totalOps > 0) { |
| 160 | + result = new ConcurrencyResult(threadCount, totalOps, opsPerSec, |
| 161 | + p(sorted, 50), p(sorted, 95), p(sorted, 99), |
| 162 | + sorted[0], sorted[sorted.length - 1], errors); |
| 163 | + } else { |
| 164 | + result = new ConcurrencyResult(threadCount, 0, 0, 0, 0, 0, 0, 0, errors); |
| 165 | + } |
| 166 | + |
| 167 | + synchronized (ALL_RESULTS) { |
| 168 | + ALL_RESULTS.add(result); |
| 169 | + } |
| 170 | + |
| 171 | + System.out.printf("[Concurrent] %2d threads: %d ops in %ds = %.1f ops/s p50=%.1fms p95=%.1fms p99=%.1fms errors=%d%n", |
| 172 | + threadCount, totalOps, MEASURE_DURATION_MS / 1000, opsPerSec, |
| 173 | + totalOps > 0 ? sorted[percentileIndex(sorted.length, 50)] / 1_000_000.0 : 0, |
| 174 | + totalOps > 0 ? sorted[percentileIndex(sorted.length, 95)] / 1_000_000.0 : 0, |
| 175 | + totalOps > 0 ? sorted[percentileIndex(sorted.length, 99)] / 1_000_000.0 : 0, |
| 176 | + errors); |
| 177 | + |
| 178 | + // Allow small error rate for CI environment transient failures |
| 179 | + int totalAttempts = totalOps + errors; |
| 180 | + double errorRate = totalAttempts > 0 ? (errors * 100.0 / totalAttempts) : 0; |
| 181 | + assertThat(errorRate) |
| 182 | + .as("Error rate at %d threads (errors=%d, total=%d)", threadCount, errors, totalAttempts) |
| 183 | + .isLessThan(MAX_ERROR_RATE_PERCENT); |
| 184 | + assertThat(totalOps).as("Total ops at %d threads", threadCount).isGreaterThan(0); |
| 185 | + } finally { |
| 186 | + executor.shutdownNow(); |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + private static long p(long[] sorted, int percentile) { |
| 191 | + return sorted[percentileIndex(sorted.length, percentile)]; |
| 192 | + } |
| 193 | + |
| 194 | + private static int percentileIndex(int length, int percentile) { |
| 195 | + return Math.min((int) Math.ceil(percentile / 100.0 * length) - 1, length - 1); |
| 196 | + } |
| 197 | +} |
0 commit comments