Debian Codegraph @

server/jetstream_benchmark_test.go

raw
1 // Copyright 2023-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //go:build !skip_js_tests && !skip_js_cluster_tests && !skip_js_cluster_tests_2
15
16 package server
17
18 import (
19 "encoding/json"
20 "fmt"
21 "math"
22 "math/bits"
23 "math/rand"
24 "os"
25 "path/filepath"
26 "runtime"
27 "strconv"
28 "strings"
29 "sync"
30 "sync/atomic"
31 "testing"
32 "time"
33
34 "github.com/nats-io/nats-server/v2/internal/fastrand"
35 "github.com/nats-io/nats.go"
36 )
37
38 func BenchmarkJetStreamConsume(b *testing.B) {
39
40 const (
41 verbose = false
42 streamName = "S"
43 subject = "s"
44 seed = 12345
45 publishTimeout = 30 * time.Second
46 PublishBatchSize = 10000
47 )
48
49 runSyncPushConsumer := func(b *testing.B, js nats.JetStreamContext, streamName string) (int, int, int) {
50 const nextMsgTimeout = 3 * time.Second
51
52 subOpts := []nats.SubOpt{
53 nats.BindStream(streamName),
54 }
55 sub, err := js.SubscribeSync(_EMPTY_, subOpts...)
56 if err != nil {
57 b.Fatalf("Failed to subscribe: %v", err)
58 }
59 defer sub.Unsubscribe()
60
61 bitset := NewBitset(uint64(b.N))
62 uniqueConsumed, duplicates, errors := 0, 0, 0
63
64 b.ResetTimer()
65
66 for uniqueConsumed < b.N {
67 msg, err := sub.NextMsg(nextMsgTimeout)
68 if err != nil {
69 b.Fatalf("No more messages (received: %d/%d)", uniqueConsumed, b.N)
70 }
71
72 metadata, mdErr := msg.Metadata()
73 if mdErr != nil {
74 errors++
75 continue
76 }
77
78 ackErr := msg.Ack()
79 if ackErr != nil {
80 errors++
81 continue
82 }
83
84 seq := metadata.Sequence.Stream
85
86 index := seq - 1
87 if bitset.get(index) {
88 duplicates++
89 continue
90 }
91
92 uniqueConsumed++
93 bitset.set(index, true)
94
95 if verbose && uniqueConsumed%1000 == 0 {
96 b.Logf("Consumed: %d/%d", bitset.count(), b.N)
97 }
98 }
99
100 b.StopTimer()
101
102 return uniqueConsumed, duplicates, errors
103 }
104
105 runAsyncPushConsumer := func(b *testing.B, js nats.JetStreamContext, streamName string, ordered, durable bool) (int, int, int) {
106 const timeout = 3 * time.Minute
107 bitset := NewBitset(uint64(b.N))
108 doneCh := make(chan bool, 1)
109 uniqueConsumed, duplicates, errors := 0, 0, 0
110
111 handleMsg := func(msg *nats.Msg) {
112 metadata, mdErr := msg.Metadata()
113 if mdErr != nil {
114 // fmt.Printf("Metadata error: %v\n", mdErr)
115 errors++
116 return
117 }
118
119 // Ordered defaults to AckNone policy, don't try to ACK
120 if !ordered {
121 ackErr := msg.Ack()
122 if ackErr != nil {
123 // fmt.Printf("Ack error: %v\n", ackErr)
124 errors++
125 return
126 }
127 }
128
129 seq := metadata.Sequence.Stream
130
131 index := seq - 1
132 if bitset.get(index) {
133 duplicates++
134 return
135 }
136
137 uniqueConsumed++
138 bitset.set(index, true)
139
140 if uniqueConsumed == b.N {
141 msg.Sub.Unsubscribe()
142 doneCh <- true
143 }
144 if verbose && uniqueConsumed%1000 == 0 {
145 b.Logf("Consumed %d/%d", uniqueConsumed, b.N)
146 }
147 }
148
149 subOpts := []nats.SubOpt{
150 nats.BindStream(streamName),
151 }
152
153 if ordered {
154 subOpts = append(subOpts, nats.OrderedConsumer())
155 }
156
157 if durable {
158 subOpts = append(subOpts, nats.Durable("c"))
159 }
160
161 sub, err := js.Subscribe(_EMPTY_, handleMsg, subOpts...)
162 if err != nil {
163 b.Fatalf("Failed to subscribe: %v", err)
164 }
165 defer sub.Unsubscribe()
166
167 b.ResetTimer()
168
169 select {
170 case <-doneCh:
171 b.StopTimer()
172 case <-time.After(timeout):
173 b.Fatalf("Timeout, %d/%d received, %d errors", uniqueConsumed, b.N, errors)
174 }
175
176 return uniqueConsumed, duplicates, errors
177 }
178
179 runPullConsumer := func(b *testing.B, js nats.JetStreamContext, streamName string, durable bool) (int, int, int) {
180 const fetchMaxWait = nats.MaxWait(3 * time.Second)
181 const fetchMaxMessages = 1000
182
183 bitset := NewBitset(uint64(b.N))
184 uniqueConsumed, duplicates, errors := 0, 0, 0
185
186 subOpts := []nats.SubOpt{
187 nats.BindStream(streamName),
188 }
189
190 consumerName := _EMPTY_ // Default ephemeral
191 if durable {
192 consumerName = "c" // Durable
193 }
194
195 sub, err := js.PullSubscribe("", consumerName, subOpts...)
196 if err != nil {
197 b.Fatalf("Failed to subscribe: %v", err)
198 }
199 defer sub.Unsubscribe()
200
201 b.ResetTimer()
202
203 fetchLoop:
204 for {
205 msgs, err := sub.Fetch(fetchMaxMessages, fetchMaxWait)
206 if err != nil {
207 b.Fatalf("Failed to fetch: %v", err)
208 }
209
210 processMsgsLoop:
211 for _, msg := range msgs {
212 metadata, mdErr := msg.Metadata()
213 if mdErr != nil {
214 errors++
215 continue processMsgsLoop
216 }
217
218 ackErr := msg.Ack()
219 if ackErr != nil {
220 errors++
221 continue processMsgsLoop
222 }
223
224 seq := metadata.Sequence.Stream
225
226 index := seq - 1
227 if bitset.get(index) {
228 duplicates++
229 continue processMsgsLoop
230 }
231
232 uniqueConsumed++
233 bitset.set(index, true)
234
235 if uniqueConsumed == b.N {
236 msg.Sub.Unsubscribe()
237 break fetchLoop
238 }
239
240 if verbose && uniqueConsumed%1000 == 0 {
241 b.Logf("Consumed %d/%d", uniqueConsumed, b.N)
242 }
243 }
244 }
245
246 b.StopTimer()
247
248 return uniqueConsumed, duplicates, errors
249 }
250
251 type ConsumerType string
252 const (
253 PushSync ConsumerType = "PUSH[Sync,Ephemeral]"
254 PushAsync ConsumerType = "PUSH[Async,Ephemeral]"
255 PushAsyncOrdered ConsumerType = "PUSH[Async,Ordered]"
256 PushAsyncDurable ConsumerType = "PUSH[Async,Durable]"
257 PullDurable ConsumerType = "PULL[Durable]"
258 PullEphemeral ConsumerType = "PULL[Ephemeral]"
259 )
260
261 benchmarksCases := []struct {
262 clusterSize int
263 replicas int
264 messageSize int
265 minMessages int
266 }{
267 {1, 1, 10, 100_000}, // Single node, 10B messages, ~1MiB minimum
268 {1, 1, 1024, 1_000}, // Single node, 1KB messages, ~1MiB minimum
269 {3, 3, 10, 100_000}, // Cluster, R3, 10B messages, ~1MiB minimum
270 {3, 3, 1024, 1_000}, // Cluster, R3, 1KB messages, ~1MiB minimum
271 }
272
273 //Each of the cases above is run with each of the consumer types
274 consumerTypes := []ConsumerType{
275 PushSync,
276 PushAsync,
277 PushAsyncOrdered,
278 PushAsyncDurable,
279 PullDurable,
280 PullEphemeral,
281 }
282
283 for _, bc := range benchmarksCases {
284
285 name := fmt.Sprintf(
286 "N=%d,R=%d,MsgSz=%db",
287 bc.clusterSize,
288 bc.replicas,
289 bc.messageSize,
290 )
291
292 b.Run(
293 name,
294 func(b *testing.B) {
295
296 for _, ct := range consumerTypes {
297 name := fmt.Sprintf(
298 "%v",
299 ct,
300 )
301 b.Run(
302 name,
303 func(b *testing.B) {
304 // Skip short runs, benchmark gets re-executed with a larger N
305 if b.N < bc.minMessages {
306 b.ResetTimer()
307 return
308 }
309
310 if verbose {
311 b.Logf("Running %s with %d messages", name, b.N)
312 }
313
314 if verbose {
315 b.Logf("Setting up %d nodes", bc.clusterSize)
316 }
317
318 cl, _, shutdown, nc, js := startJSClusterAndConnect(b, bc.clusterSize)
319 defer shutdown()
320 defer nc.Close()
321
322 if verbose {
323 b.Logf("Creating stream with R=%d", bc.replicas)
324 }
325 streamConfig := &nats.StreamConfig{
326 Name: streamName,
327 Subjects: []string{subject},
328 Replicas: bc.replicas,
329 }
330 if _, err := js.AddStream(streamConfig); err != nil {
331 b.Fatalf("Error creating stream: %v", err)
332 }
333
334 // If replicated resource, connect to stream leader for lower variability
335 if bc.replicas > 1 {
336 connectURL := cl.streamLeader("$G", streamName).ClientURL()
337 nc.Close()
338 _, js = jsClientConnectURL(b, connectURL)
339 }
340
341 message := make([]byte, bc.messageSize)
342 rand.New(rand.NewSource(int64(seed))).Read(message)
343
344 // Publish b.N messages to the stream (in batches)
345 for i := 1; i <= b.N; i++ {
346 fastRandomMutation(message, 10)
347 _, err := js.PublishAsync(subject, message)
348 if err != nil {
349 b.Fatalf("Failed to publish: %s", err)
350 }
351 // Limit outstanding published messages to PublishBatchSize
352 if i%PublishBatchSize == 0 || i == b.N {
353 select {
354 case <-js.PublishAsyncComplete():
355 if verbose {
356 b.Logf("Published %d/%d messages", i, b.N)
357 }
358 case <-time.After(publishTimeout):
359 b.Fatalf("Publish timed out")
360 }
361 }
362 }
363
364 // Set size of each operation, for throughput calculation
365 b.SetBytes(int64(bc.messageSize))
366
367 // Discard time spent during setup
368 // Consumer may reset again further in
369 b.ResetTimer()
370
371 var consumed, duplicates, errors int
372
373 const (
374 ordered = true
375 unordered = false
376 durable = true
377 ephemeral = false
378 )
379
380 switch ct {
381 case PushSync:
382 consumed, duplicates, errors = runSyncPushConsumer(b, js, streamName)
383 case PushAsync:
384 consumed, duplicates, errors = runAsyncPushConsumer(b, js, streamName, unordered, ephemeral)
385 case PushAsyncOrdered:
386 consumed, duplicates, errors = runAsyncPushConsumer(b, js, streamName, ordered, ephemeral)
387 case PushAsyncDurable:
388 consumed, duplicates, errors = runAsyncPushConsumer(b, js, streamName, unordered, durable)
389 case PullDurable:
390 consumed, duplicates, errors = runPullConsumer(b, js, streamName, durable)
391 case PullEphemeral:
392 consumed, duplicates, errors = runPullConsumer(b, js, streamName, ephemeral)
393 default:
394 b.Fatalf("Unknown consumer type: %v", ct)
395 }
396
397 // Benchmark ends here, (consumer may have stopped earlier)
398 b.StopTimer()
399
400 if consumed != b.N {
401 b.Fatalf("Something doesn't add up: %d != %d", consumed, b.N)
402 }
403
404 b.ReportMetric(float64(duplicates)*100/float64(b.N), "%dupe")
405 b.ReportMetric(float64(errors)*100/float64(b.N), "%error")
406 },
407 )
408 }
409 },
410 )
411 }
412 }
413
414 // BenchmarkJetStreamConsumeFilteredContiguous verifies the fix in
415 // https://github.com/nats-io/nats-server/pull/7015 and should
416 // capture future regressions.
417 func BenchmarkJetStreamConsumeFilteredContiguous(b *testing.B) {
418 clusterSizeCases := []struct {
419 clusterSize int // Single node or cluster
420 replicas int // Stream replicas
421 storage nats.StorageType // Stream storage
422 filters int // How many subject filters?
423 }{
424 {1, 1, nats.MemoryStorage, 1},
425 {1, 1, nats.MemoryStorage, 2},
426 {3, 3, nats.MemoryStorage, 1},
427 {3, 3, nats.MemoryStorage, 2},
428 {1, 1, nats.FileStorage, 1},
429 {1, 1, nats.FileStorage, 2},
430 {3, 3, nats.FileStorage, 1},
431 {3, 3, nats.FileStorage, 2},
432 }
433
434 for _, cs := range clusterSizeCases {
435 name := fmt.Sprintf(
436 "N=%d,R=%d,storage=%s",
437 cs.clusterSize,
438 cs.replicas,
439 cs.storage.String(),
440 )
441 if cs.filters != 2 { // historical default is 2
442 name = name + ",SF"
443 }
444 b.Run(name, func(b *testing.B) {
445 _, _, shutdown, nc, js := startJSClusterAndConnect(b, cs.clusterSize)
446 defer shutdown()
447 defer nc.Close()
448
449 var msgs = b.N
450 payload := make([]byte, 1024)
451
452 _, err := js.AddStream(&nats.StreamConfig{
453 Name: "test",
454 Subjects: []string{"foo"},
455 Retention: nats.LimitsPolicy,
456 Storage: cs.storage,
457 Replicas: cs.replicas,
458 })
459 require_NoError(b, err)
460
461 for range msgs {
462 _, err = js.Publish("foo", payload)
463 require_NoError(b, err)
464 }
465
466 // Subject filters deliberately vary from the stream, ensures that we hit
467 // the right paths in the filestore, rather than detecting 1:1 overlap.
468 ocfg := &nats.ConsumerConfig{
469 Name: "test_consumer",
470 DeliverPolicy: nats.DeliverAllPolicy,
471 AckPolicy: nats.AckNonePolicy,
472 Replicas: cs.replicas,
473 MemoryStorage: true,
474 }
475 switch cs.filters {
476 case 1:
477 ocfg.FilterSubject = "foo"
478 case 2:
479 ocfg.FilterSubjects = []string{"foo", "bar"}
480 }
481 _, err = js.AddConsumer("test", ocfg)
482 require_NoError(b, err)
483
484 ps, err := js.PullSubscribe("foo", _EMPTY_, nats.Bind("test", "test_consumer"))
485 require_NoError(b, err)
486
487 b.SetBytes(int64(len(payload)))
488 b.ReportAllocs()
489 b.ResetTimer()
490 for range msgs {
491 msgs, err := ps.Fetch(1)
492 require_NoError(b, err)
493 require_Len(b, len(msgs), 1)
494 }
495 b.StopTimer()
496 })
497 }
498 }
499
500 func BenchmarkJetStreamConsumeWithFilters(b *testing.B) {
501 const (
502 verbose = false
503 streamName = "S"
504 subjectPrefix = "s"
505 seed = 123456
506 messageSize = 32
507 consumerReplicas = 1
508 domainNameLength = 36 // Length of domain portion of subject, must be an even number
509 publishBatchSize = 1000
510 publishTimeout = 10 * time.Second
511 )
512
513 clusterSizeCases := []struct {
514 clusterSize int // Single node or cluster
515 replicas int // Stream replicas
516 storage nats.StorageType // Stream storage
517 }{
518 {1, 1, nats.MemoryStorage},
519 {3, 3, nats.MemoryStorage},
520 {1, 1, nats.FileStorage},
521 {3, 3, nats.FileStorage},
522 }
523
524 benchmarksCases := []struct {
525 domains int // Number of distinct domains
526 subjectsPerDomain int // Number of distinct subjects within each domain
527 filters int // Number of filters (<prefix>.<domain>.>) per consumer
528 concurrentConsumers int // Number of consumer running
529
530 }{
531 {100, 10, 5, 12},
532 {1000, 10, 25, 12},
533 {10_000, 10, 50, 12},
534 }
535
536 for _, cs := range clusterSizeCases {
537 name := fmt.Sprintf(
538 "N=%d,R=%d,storage=%s",
539 cs.clusterSize,
540 cs.replicas,
541 cs.storage.String(),
542 )
543 b.Run(
544 name,
545 func(b *testing.B) {
546
547 for _, bc := range benchmarksCases {
548
549 name := fmt.Sprintf(
550 "D=%d,DS=%d,F=%d,C=%d",
551 bc.domains,
552 bc.subjectsPerDomain,
553 bc.filters,
554 bc.concurrentConsumers,
555 )
556
557 b.Run(
558 name,
559 func(b *testing.B) {
560
561 cl, s, shutdown, nc, js := startJSClusterAndConnect(b, cs.clusterSize)
562 defer shutdown()
563 defer nc.Close()
564
565 if verbose {
566 b.Logf("Creating stream with R=%d", cs.replicas)
567 }
568 streamConfig := &nats.StreamConfig{
569 Name: streamName,
570 Subjects: []string{subjectPrefix + ".>"},
571 Storage: cs.storage,
572 Retention: nats.LimitsPolicy,
573 MaxAge: time.Hour,
574 Duplicates: 10 * time.Second,
575 Discard: nats.DiscardOld,
576 NoAck: false,
577 MaxMsgs: -1,
578 MaxBytes: -1,
579 MaxConsumers: -1,
580 Replicas: 1,
581 MaxMsgsPerSubject: 1,
582 }
583 if _, err := js.AddStream(streamConfig); err != nil {
584 b.Fatalf("Error creating stream: %v", err)
585 }
586
587 // If replicated resource, connect to stream leader for lower variability
588 connectURL := s.ClientURL()
589 if cs.replicas > 1 {
590 connectURL = cl.streamLeader("$G", streamName).ClientURL()
591 nc.Close()
592 _, js = jsClientConnectURL(b, connectURL)
593 }
594
595 rng := rand.New(rand.NewSource(int64(seed)))
596 message := make([]byte, messageSize)
597 domain := make([]byte, domainNameLength/2)
598
599 domains := make([]string, 0, bc.domains*bc.subjectsPerDomain)
600
601 // Publish one message per subject for each domain
602 published := 0
603 totalMessages := bc.domains * bc.subjectsPerDomain
604 for d := 1; d <= bc.domains; d++ {
605 rng.Read(domain)
606 for s := 1; s <= bc.subjectsPerDomain; s++ {
607 rng.Read(message)
608 domainString := fmt.Sprintf("%X", domain)
609 domains = append(domains, domainString)
610 subject := fmt.Sprintf("%s.%s.%d", subjectPrefix, domainString, s)
611 _, err := js.PublishAsync(subject, message)
612 if err != nil {
613 b.Fatalf("failed to publish: %s", err)
614 }
615 published += 1
616
617 // Wait for all pending to be published before trying to publish the next batch
618 if published%publishBatchSize == 0 || published == totalMessages {
619 select {
620 case <-js.PublishAsyncComplete():
621 if verbose {
622 b.Logf("Published %d/%d messages", published, totalMessages)
623 }
624 case <-time.After(publishTimeout):
625 b.Fatalf("Publish timed out")
626 }
627 }
628
629 }
630 }
631
632 // Number of messages that each new consumer expects to consume
633 messagesPerIteration := bc.filters * bc.subjectsPerDomain
634
635 // Each call to 'subscribe_consume_unsubscribe' is one benchmark operation.
636 // i.e. subscribe_consume_unsubscribe will be called a total of b.N times (split among C threads)
637 // Each operation consists of:
638 // - Create filter
639 // - Create consumer / Subscribe
640 // - Consume expected number of messages
641 // - Unsubscribe
642 subscribeConsumeUnsubscribe := func(js nats.JetStreamContext, rng *rand.Rand) {
643
644 // Select F unique domains to create F non-overlapping filters
645 filterDomains := make(map[string]bool, bc.filters)
646 filters := make([]string, 0, bc.filters)
647 for len(filterDomains) < bc.filters {
648 domain := domains[rng.Intn(len(domains))]
649 if _, found := filterDomains[domain]; found {
650 // Collision with existing filter, try again
651 continue
652 }
653 filterDomains[domain] = true
654 filters = append(filters, fmt.Sprintf("%s.%s.>", subjectPrefix, domain))
655 }
656
657 if verbose {
658 b.Logf("Subscribe with filters: %+v", filters)
659 }
660
661 // Consumer callback
662 received := 0
663 consumeWg := sync.WaitGroup{}
664 consumeWg.Add(1)
665 cb := func(msg *nats.Msg) {
666 received += 1
667 if received == messagesPerIteration {
668 consumeWg.Done()
669 if verbose {
670 b.Logf("Received %d/%d messages", received, messagesPerIteration)
671 }
672 }
673 }
674
675 // Create consumer
676 subOpts := []nats.SubOpt{
677 nats.BindStream(streamName),
678 nats.OrderedConsumer(),
679 nats.ConsumerReplicas(consumerReplicas),
680 nats.ConsumerFilterSubjects(filters...),
681 nats.ConsumerMemoryStorage(),
682 }
683
684 var sub *nats.Subscription
685
686 sub, err := js.Subscribe("", cb, subOpts...)
687 if err != nil {
688 b.Fatalf("Failed to subscribe: %s", err)
689 }
690
691 defer func(sub *nats.Subscription) {
692 err := sub.Unsubscribe()
693 if err != nil {
694 b.Logf("Failed to unsubscribe: %s", err)
695 }
696 }(sub)
697
698 consumeWg.Wait()
699 }
700
701 // Wait for all consumer threads and main to be ready
702 wgReady := sync.WaitGroup{}
703 wgReady.Add(bc.concurrentConsumers + 1)
704 // Wait until all consumer threads have completed
705 wgCompleted := sync.WaitGroup{}
706 wgCompleted.Add(bc.concurrentConsumers)
707 // Operations left for consumer threads
708 opsCount := atomic.Int32{}
709 opsCount.Store(int32(b.N))
710
711 // Start a pool of C goroutines, each one with a dedicated connection.
712 for i := 1; i <= bc.concurrentConsumers; i++ {
713 go func(consumerId int) {
714
715 // Connect
716 nc, js := jsClientConnectURL(b, connectURL)
717 defer nc.Close()
718
719 // Signal completion of work
720 defer wgCompleted.Done()
721
722 rng := rand.New(rand.NewSource(int64(seed + consumerId)))
723
724 // Ready, wait for everyone else
725 wgReady.Done()
726 wgReady.Wait()
727
728 completed := 0
729 for opsCount.Add(-1) >= 0 {
730 subscribeConsumeUnsubscribe(js, rng)
731 completed += 1
732 }
733 if verbose {
734 b.Logf("Consumer thread %d completed %d of %d operations", consumerId, completed, b.N)
735 }
736 }(i)
737 }
738
739 // Wait for all consumers to be ready
740 wgReady.Done()
741 wgReady.Wait()
742
743 // Start measuring time
744 b.ResetTimer()
745
746 // Wait for consumers to have chewed through b.N operations
747 wgCompleted.Wait()
748 b.StopTimer()
749
750 // Throughput is not very important in this benchmark since each operation includes
751 // subscribe, unsubscribe and retrieves just a few bytes
752 //b.SetBytes(int64(messageSize * messagesPerIteration))
753 },
754 )
755 }
756 },
757 )
758 }
759 }
760
761 func BenchmarkJetStreamPublish(b *testing.B) {
762
763 const (
764 verbose = false
765 seed = 12345
766 streamName = "S"
767 )
768
769 runSyncPublisher := func(b *testing.B, js nats.JetStreamContext, messageSize int, subjects []string) (int, int) {
770 published, errors := 0, 0
771 message := make([]byte, messageSize)
772 rand.New(rand.NewSource(int64(seed))).Read(message)
773
774 b.ResetTimer()
775
776 for i := 1; i <= b.N; i++ {
777 fastRandomMutation(message, 10)
778 subject := subjects[fastrand.Uint32n(uint32(len(subjects)))]
779 _, pubErr := js.Publish(subject, message)
780 if pubErr != nil {
781 errors++
782 } else {
783 published++
784 }
785
786 if verbose && i%1000 == 0 {
787 b.Logf("Published %d/%d, %d errors", i, b.N, errors)
788 }
789 }
790
791 b.StopTimer()
792
793 return published, errors
794 }
795
796 runAsyncPublisher := func(b *testing.B, js nats.JetStreamContext, messageSize int, subjects []string, asyncWindow int) (int, int) {
797 const publishCompleteMaxWait = 30 * time.Second
798 rng := rand.New(rand.NewSource(int64(seed)))
799 message := make([]byte, messageSize)
800 rng.Read(message)
801
802 published, errors := 0, 0
803
804 b.ResetTimer()
805
806 for published < b.N {
807
808 // Normally publish a full batch (of size `asyncWindow`)
809 publishBatchSize := asyncWindow
810 // Unless fewer are left to complete the benchmark
811 if b.N-published < asyncWindow {
812 publishBatchSize = b.N - published
813 }
814
815 pending := make([]nats.PubAckFuture, 0, publishBatchSize)
816
817 for i := 0; i < publishBatchSize; i++ {
818 fastRandomMutation(message, 10)
819 subject := subjects[rng.Intn(len(subjects))]
820 pubAckFuture, err := js.PublishAsync(subject, message)
821 if err != nil {
822 errors++
823 continue
824 }
825 pending = append(pending, pubAckFuture)
826 }
827
828 // All in this batch published, wait for completed
829 select {
830 case <-js.PublishAsyncComplete():
831 case <-time.After(publishCompleteMaxWait):
832 b.Fatalf("Publish timed out")
833 }
834
835 // Verify one by one if they were published successfully
836 for _, pubAckFuture := range pending {
837 select {
838 case <-pubAckFuture.Ok():
839 published++
840 case <-pubAckFuture.Err():
841 errors++
842 default:
843 b.Fatalf("PubAck is still pending after publish completed")
844 }
845 }
846
847 if verbose {
848 b.Logf("Published %d/%d", published, b.N)
849 }
850 }
851
852 b.StopTimer()
853
854 return published, errors
855 }
856
857 type PublishType string
858 const (
859 Sync PublishType = "Sync"
860 Async PublishType = "Async"
861 )
862
863 benchmarksCases := []struct {
864 clusterSize int
865 replicas int
866 messageSize int
867 numSubjects int
868 }{
869 {1, 1, 10, 1}, // Single node, 10B messages
870 {1, 1, 1024, 1}, // Single node, 1KB messages
871 {3, 3, 10, 1}, // 3-nodes cluster, R=3, 10B messages
872 {3, 3, 1024, 1}, // 3-nodes cluster, R=3, 1KB messages
873 {3, 3, 10, 1}, // 3-nodes cluster, R=3, 10B messages (async flush)
874 {3, 3, 1024, 1}, // 3-nodes cluster, R=3, 1KB messages (async flush)
875 }
876
877 // All the cases above are run with each of the publisher cases below
878 publisherCases := []struct {
879 pType PublishType
880 asyncWindow int
881 }{
882 {Sync, -1},
883 {Async, 1000},
884 {Async, 4000},
885 {Async, 8000},
886 }
887
888 for _, bc := range benchmarksCases {
889 name := fmt.Sprintf(
890 "N=%d,R=%d,MsgSz=%db,Subjs=%d",
891 bc.clusterSize,
892 bc.replicas,
893 bc.messageSize,
894 bc.numSubjects,
895 )
896 b.Run(
897 name,
898 func(b *testing.B) {
899
900 for _, pc := range publisherCases {
901 name := fmt.Sprintf("%v", pc.pType)
902 if pc.pType == Async && pc.asyncWindow > 0 {
903 name = fmt.Sprintf("%s[W:%d]", name, pc.asyncWindow)
904 }
905
906 b.Run(
907 name,
908 func(b *testing.B) {
909
910 subjects := make([]string, bc.numSubjects)
911 for i := 0; i < bc.numSubjects; i++ {
912 subjects[i] = fmt.Sprintf("s-%d", i+1)
913 }
914
915 if verbose {
916 b.Logf("Running %s with %d ops", name, b.N)
917 }
918
919 if verbose {
920 b.Logf("Setting up %d nodes", bc.clusterSize)
921 }
922
923 cl, _, shutdown, nc, _ := startJSClusterAndConnect(b, bc.clusterSize)
924 defer shutdown()
925 defer nc.Close()
926
927 jsOpts := []nats.JSOpt{
928 nats.MaxWait(10 * time.Second),
929 }
930
931 if pc.asyncWindow > 0 && pc.pType == Async {
932 jsOpts = append(jsOpts, nats.PublishAsyncMaxPending(pc.asyncWindow))
933 }
934
935 js, err := nc.JetStream(jsOpts...)
936 if err != nil {
937 b.Fatalf("Unexpected error getting JetStream context: %v", err)
938 }
939
940 if verbose {
941 b.Logf("Creating stream with R=%d and %d input subjects", bc.replicas, bc.numSubjects)
942 }
943 _, err = jsStreamCreate(b, nc, &StreamConfig{
944 Name: streamName,
945 Subjects: subjects,
946 Replicas: bc.replicas,
947 Storage: FileStorage,
948 })
949 if err != nil {
950 b.Fatalf("Error creating stream: %v", err)
951 }
952
953 // If replicated resource, connect to stream leader for lower variability
954 if bc.replicas > 1 {
955 connectURL := cl.streamLeader("$G", streamName).ClientURL()
956 nc.Close()
957 nc, err = nats.Connect(connectURL)
958 if err != nil {
959 b.Fatalf("Failed to create client connection to stream leader: %v", err)
960 }
961 defer nc.Close()
962 js, err = nc.JetStream(jsOpts...)
963 if err != nil {
964 b.Fatalf("Unexpected error getting JetStream context for stream leader: %v", err)
965 }
966 }
967
968 if verbose {
969 b.Logf("Running %v publisher with message size: %dB", pc.pType, bc.messageSize)
970 }
971
972 b.SetBytes(int64(bc.messageSize))
973
974 // Benchmark starts here
975 b.ResetTimer()
976
977 var published, errors int
978 switch pc.pType {
979 case Sync:
980 published, errors = runSyncPublisher(b, js, bc.messageSize, subjects)
981 case Async:
982 published, errors = runAsyncPublisher(b, js, bc.messageSize, subjects, pc.asyncWindow)
983 }
984
985 // Benchmark ends here
986 b.StopTimer()
987
988 if published+errors != b.N {
989 b.Fatalf("Something doesn't add up: %d + %d != %d", published, errors, b.N)
990 }
991
992 b.ReportMetric(float64(errors)*100/float64(b.N), "%error")
993 },
994 )
995 }
996 },
997 )
998 }
999 }
1000
1001 func BenchmarkJetStreamMetaSnapshot(b *testing.B) {
1002 c := createJetStreamClusterExplicit(b, "R3S", 3)
1003 defer c.shutdown()
1004
1005 setup := func(reqLevel string) *jetStream {
1006 ml := c.leader()
1007 acc, js := ml.globalAccount(), ml.getJetStream()
1008 n := js.getMetaGroup()
1009
1010 // Create all streams and consumers.
1011 numStreams := 200
1012 numConsumers := 500
1013 ci := &ClientInfo{Cluster: "R3S", Account: globalAccountName}
1014 js.mu.Lock()
1015 metadata := map[string]string{JSRequiredLevelMetadataKey: reqLevel}
1016 for i := 0; i < numStreams; i++ {
1017 scfg := &StreamConfig{
1018 Name: fmt.Sprintf("STREAM-%d", i),
1019 Subjects: []string{fmt.Sprintf("SUBJECT-%d", i)},
1020 Storage: MemoryStorage,
1021 Metadata: metadata,
1022 }
1023 cfg, _ := ml.checkStreamCfg(scfg, acc, false)
1024 rg, _ := js.createGroupForStream(ci, &cfg)
1025 sa := &streamAssignment{Group: rg, Sync: syncSubjForStream(), Config: &cfg, Client: ci, Created: time.Now().UTC()}
1026 n.Propose(n.Term(), encodeAddStreamAssignment(sa))
1027
1028 for j := 0; j < numConsumers; j++ {
1029 ccfg := &ConsumerConfig{
1030 Durable: fmt.Sprintf("CONSUMER-%d", j),
1031 MemoryStorage: true,
1032 Metadata: metadata,
1033 }
1034 selectedLimits, _, _, _ := acc.selectLimits(ccfg.replicas(&cfg))
1035 srvLim := &ml.getOpts().JetStreamLimits
1036 setConsumerConfigDefaults(ccfg, &cfg, srvLim, selectedLimits, false)
1037 rg, _ = js.cluster.createGroupForConsumer(ccfg, sa)
1038 ca := &consumerAssignment{Group: rg, Stream: cfg.Name, Name: ccfg.Durable, Config: ccfg, Client: ci, Created: time.Now().UTC()}
1039 n.Propose(n.Term(), encodeAddConsumerAssignment(ca))
1040 }
1041 }
1042 js.mu.Unlock()
1043
1044 // Wait for all servers to have created all assets.
1045 checkFor(b, 20*time.Second, 200*time.Millisecond, func() error {
1046 for _, s := range c.servers {
1047 sjs := s.getJetStream()
1048 sjs.mu.RLock()
1049 streams := sjs.cluster.streams[globalAccountName]
1050 if len(streams) != numStreams {
1051 sjs.mu.RUnlock()
1052 return fmt.Errorf("expected %d streams, got %d", numStreams, len(streams))
1053 }
1054 for _, sa := range streams {
1055 if nc := len(sa.consumers); nc != numConsumers {
1056 sjs.mu.RUnlock()
1057 return fmt.Errorf("expected %d consumers, got %d", numConsumers, nc)
1058 }
1059 }
1060 sjs.mu.RUnlock()
1061 }
1062 return nil
1063 })
1064 return js
1065 }
1066
1067 for _, t := range []struct {
1068 title string
1069 reqLevel string
1070 }{
1071 {title: "Default", reqLevel: "0"},
1072 {title: "AllUnsupported", reqLevel: strconv.Itoa(math.MaxInt)},
1073 } {
1074 b.Run(t.title, func(b *testing.B) {
1075 js := setup(t.reqLevel)
1076 b.ResetTimer()
1077 for range b.N {
1078 js.metaSnapshot()
1079 }
1080 b.StopTimer()
1081 })
1082 }
1083 }
1084
1085 func BenchmarkJetStreamCounters(b *testing.B) {
1086 const (
1087 verbose = false
1088 seed = 12345
1089 streamName = "S"
1090 )
1091
1092 // We don't actually create real sourcing streams, we just populate
1093 // the Nats-Counter-Sources header to make it look like we have some,
1094 // so that we can see how the code performs for bringing forward the
1095 // latest headers each time.
1096 generateSources := func(t testing.TB, count int) string {
1097 t.Helper()
1098 sources := CounterSources{}
1099 for i := range count {
1100 streamName := fmt.Sprintf("STREAM_%d", i%10)
1101 subjectName := fmt.Sprintf("subject.%d", i)
1102 if sources[streamName] == nil {
1103 sources[streamName] = map[string]string{}
1104 }
1105 sources[streamName][subjectName] = "12345"
1106 }
1107 j, err := json.Marshal(sources)
1108 require_NoError(t, err)
1109 return string(j)
1110 }
1111
1112 runSyncPublisher := func(b *testing.B, js nats.JetStreamContext, subjects []string, sources int) (int, int) {
1113 published, errors := 0, 0
1114 msg := &nats.Msg{
1115 Header: nats.Header{},
1116 }
1117 msg.Header.Set(JSMessageIncr, "1")
1118 if sources > 0 {
1119 msg.Header.Set(JSMessageCounterSources, generateSources(b, sources))
1120 }
1121 b.ResetTimer()
1122
1123 for i := 1; i <= b.N; i++ {
1124 msg.Subject = subjects[fastrand.Uint32n(uint32(len(subjects)))]
1125 if _, pubErr := js.PublishMsg(msg); pubErr != nil {
1126 errors++
1127 } else {
1128 published++
1129 }
1130
1131 if verbose && i%1000 == 0 {
1132 b.Logf("Published %d/%d, %d errors", i, b.N, errors)
1133 }
1134 }
1135
1136 b.StopTimer()
1137 return published, errors
1138 }
1139
1140 runAsyncPublisher := func(b *testing.B, js nats.JetStreamContext, subjects []string, sources int, asyncWindow int) (int, int) {
1141 const publishCompleteMaxWait = 30 * time.Second
1142 msg := &nats.Msg{
1143 Header: nats.Header{},
1144 }
1145 msg.Header.Set(JSMessageIncr, "1")
1146 if sources > 0 {
1147 msg.Header.Set(JSMessageCounterSources, generateSources(b, sources))
1148 }
1149 published, errors := 0, 0
1150 b.ResetTimer()
1151
1152 for published < b.N {
1153 // Normally publish a full batch (of size `asyncWindow`)
1154 publishBatchSize := min(b.N-published, asyncWindow)
1155 pending := make([]nats.PubAckFuture, 0, publishBatchSize)
1156
1157 for range publishBatchSize {
1158 msg.Subject = subjects[fastrand.Uint32n(uint32(len(subjects)))]
1159 pubAckFuture, err := js.PublishMsgAsync(msg)
1160 if err != nil {
1161 errors++
1162 continue
1163 }
1164 pending = append(pending, pubAckFuture)
1165 }
1166
1167 // All in this batch published, wait for completed
1168 select {
1169 case <-js.PublishAsyncComplete():
1170 case <-time.After(publishCompleteMaxWait):
1171 b.Fatalf("Publish timed out")
1172 }
1173
1174 // Verify one by one if they were published successfully
1175 for _, pubAckFuture := range pending {
1176 select {
1177 case <-pubAckFuture.Ok():
1178 published++
1179 case <-pubAckFuture.Err():
1180 errors++
1181 default:
1182 b.Fatalf("PubAck is still pending after publish completed")
1183 }
1184 }
1185
1186 if verbose {
1187 b.Logf("Published %d/%d", published, b.N)
1188 }
1189 }
1190
1191 b.StopTimer()
1192 return published, errors
1193 }
1194
1195 type PublishType string
1196 const (
1197 Sync PublishType = "Sync"
1198 Async PublishType = "Async"
1199 )
1200
1201 type benchmarksCase struct {
1202 storageType StorageType
1203 clusterSize int
1204 replicas int
1205 numSubjects int
1206 sources int
1207 }
1208 var benchmarksCases []benchmarksCase
1209 for _, storage := range []StorageType{FileStorage, MemoryStorage} {
1210 for _, replicas := range []int{1, 3} {
1211 for _, numSubjects := range []int{1, 1000} {
1212 for _, sources := range []int{0, 10, 25, 250} {
1213 benchmarksCases = append(benchmarksCases, benchmarksCase{
1214 storageType: storage,
1215 clusterSize: 3,
1216 replicas: replicas,
1217 numSubjects: numSubjects,
1218 sources: sources,
1219 })
1220 }
1221 }
1222 }
1223 }
1224
1225 // All the cases above are run with each of the publisher cases below
1226 publisherCases := []struct {
1227 pType PublishType
1228 asyncWindow int
1229 }{
1230 {Sync, -1},
1231 {Async, 1000},
1232 {Async, 4000},
1233 {Async, 8000},
1234 }
1235
1236 for _, bc := range benchmarksCases {
1237 name := fmt.Sprintf(
1238 "S=%s,N=%d,R=%d,Subjs=%d,Srcs=%d",
1239 bc.storageType,
1240 bc.clusterSize,
1241 bc.replicas,
1242 bc.numSubjects,
1243 bc.sources,
1244 )
1245
1246 b.Run(name, func(b *testing.B) {
1247 for _, pc := range publisherCases {
1248 name := fmt.Sprintf("%v", pc.pType)
1249 if pc.pType == Async && pc.asyncWindow > 0 {
1250 name = fmt.Sprintf("%s[W:%d]", name, pc.asyncWindow)
1251 }
1252
1253 b.Run(name, func(b *testing.B) {
1254 subjects := make([]string, bc.numSubjects)
1255 for i := range bc.numSubjects {
1256 subjects[i] = fmt.Sprintf("s-%d", i+1)
1257 }
1258
1259 if verbose {
1260 b.Logf("Running %s with %d ops", name, b.N)
1261 }
1262
1263 if verbose {
1264 b.Logf("Setting up %d nodes", bc.clusterSize)
1265 }
1266
1267 cl, _, shutdown, nc, _ := startJSClusterAndConnect(b, bc.clusterSize)
1268 defer shutdown()
1269 defer nc.Close()
1270
1271 jsOpts := []nats.JSOpt{
1272 nats.MaxWait(10 * time.Second),
1273 }
1274
1275 if pc.asyncWindow > 0 && pc.pType == Async {
1276 jsOpts = append(jsOpts, nats.PublishAsyncMaxPending(pc.asyncWindow))
1277 }
1278
1279 js, err := nc.JetStream(jsOpts...)
1280 if err != nil {
1281 b.Fatalf("Unexpected error getting JetStream context: %v", err)
1282 }
1283
1284 if verbose {
1285 b.Logf("Creating stream with R=%d and %d input subjects", bc.replicas, bc.numSubjects)
1286 }
1287 if _, err := jsStreamCreate(b, nc, &StreamConfig{
1288 Name: streamName,
1289 Storage: bc.storageType,
1290 Subjects: subjects,
1291 Replicas: bc.replicas,
1292 AllowMsgCounter: true,
1293 }); err != nil {
1294 b.Fatalf("Error creating stream: %v", err)
1295 }
1296
1297 // If replicated resource, connect to stream leader for lower variability
1298 if bc.replicas > 1 {
1299 connectURL := cl.streamLeader("$G", streamName).ClientURL()
1300 nc.Close()
1301 nc, err = nats.Connect(connectURL)
1302 if err != nil {
1303 b.Fatalf("Failed to create client connection to stream leader: %v", err)
1304 }
1305 defer nc.Close()
1306 js, err = nc.JetStream(jsOpts...)
1307 if err != nil {
1308 b.Fatalf("Unexpected error getting JetStream context for stream leader: %v", err)
1309 }
1310 }
1311
1312 if verbose {
1313 b.Logf("Running %v publisher", pc.pType)
1314 }
1315
1316 // Benchmark starts here
1317 b.ResetTimer()
1318
1319 var published, errors int
1320 switch pc.pType {
1321 case Sync:
1322 published, errors = runSyncPublisher(b, js, subjects, bc.sources)
1323 case Async:
1324 published, errors = runAsyncPublisher(b, js, subjects, bc.sources, pc.asyncWindow)
1325 }
1326
1327 // Benchmark ends here
1328 b.StopTimer()
1329
1330 if published+errors != b.N {
1331 b.Fatalf("Something doesn't add up: %d + %d != %d", published, errors, b.N)
1332 }
1333
1334 b.ReportMetric(float64(errors)*100/float64(b.N), "%error")
1335 })
1336 }
1337 })
1338 }
1339 }
1340
1341 func BenchmarkJetStreamInterestStreamWithLimit(b *testing.B) {
1342
1343 const (
1344 verbose = true
1345 seed = 12345
1346 publishBatchSize = 100
1347 messageSize = 256
1348 numSubjects = 2500
1349 subjectPrefix = "S"
1350 numPublishers = 4
1351 randomData = true
1352 warmupMessages = 1
1353 )
1354
1355 if verbose {
1356 b.Logf(
1357 "BatchSize: %d, MsgSize: %d, Subjects: %d, Publishers: %d, Random Message: %v",
1358 publishBatchSize,
1359 messageSize,
1360 numSubjects,
1361 numPublishers,
1362 randomData,
1363 )
1364 }
1365
1366 // Benchmark parameters: sub-benchmarks are executed for every combination of the following 3 groups
1367 // Unless a more restrictive filter is specified, e.g.:
1368 // BenchmarkJetStreamInterestStreamWithLimit/.*R=3.*/Storage=Memory/unlimited
1369
1370 // Parameter: Number of nodes and number of stream replicas
1371 clusterAndReplicasCases := []struct {
1372 clusterSize int
1373 replicas int
1374 }{
1375 {1, 1}, // Single node, R=1
1376 {3, 3}, // 3-nodes cluster, R=3
1377 }
1378
1379 // Parameter: Stream storage type
1380 storageTypeCases := []nats.StorageType{
1381 nats.MemoryStorage,
1382 nats.FileStorage,
1383 }
1384
1385 // Parameter: Stream limit configuration
1386 limitConfigCases := map[string]func(*nats.StreamConfig){
1387 "unlimited": func(config *nats.StreamConfig) {
1388 },
1389 "MaxMsg=1000": func(config *nats.StreamConfig) {
1390 config.MaxMsgs = 100
1391 },
1392 "MaxMsg=10": func(config *nats.StreamConfig) {
1393 config.MaxMsgs = 10
1394 },
1395 "MaxPerSubject=10": func(config *nats.StreamConfig) {
1396 config.MaxMsgsPerSubject = 10
1397 },
1398 "MaxAge=1s": func(config *nats.StreamConfig) {
1399 config.MaxAge = 1 * time.Second
1400 },
1401 "MaxBytes=1MB": func(config *nats.StreamConfig) {
1402 config.MaxBytes = 1024 * 1024
1403 },
1404 }
1405
1406 // Context shared by publishers routines
1407 type PublishersContext = struct {
1408 readyWg sync.WaitGroup
1409 completedWg sync.WaitGroup
1410 messagesLeft int
1411 lock sync.Mutex
1412 errors int
1413 }
1414
1415 // Helper: Publish synchronously as Goroutine
1416 publish := func(publisherId int, ctx *PublishersContext, js nats.JetStreamContext) {
1417 defer ctx.completedWg.Done()
1418 errors := 0
1419 messageBuf := make([]byte, messageSize)
1420 rand.New(rand.NewSource(int64(seed + publisherId))).Read(messageBuf)
1421
1422 // Warm up: publish a few messages
1423 for i := 0; i < warmupMessages; i++ {
1424 subject := fmt.Sprintf("%s.%d", subjectPrefix, fastrand.Uint32n(numSubjects))
1425 if randomData {
1426 fastRandomMutation(messageBuf, 10)
1427 }
1428 _, err := js.Publish(subject, messageBuf)
1429 if err != nil {
1430 b.Logf("Warning: failed to publish warmup message: %s", err)
1431 }
1432 }
1433
1434 // Signal this publisher is ready
1435 ctx.readyWg.Done()
1436
1437 for {
1438 // Obtain a batch of messages to publish
1439 batchSize := 0
1440 {
1441 ctx.lock.Lock()
1442 if ctx.messagesLeft >= publishBatchSize {
1443 batchSize = publishBatchSize
1444 } else if ctx.messagesLeft < publishBatchSize {
1445 batchSize = ctx.messagesLeft
1446 }
1447 ctx.messagesLeft -= batchSize
1448 ctx.lock.Unlock()
1449 }
1450
1451 // Nothing left to publish, terminate
1452 if batchSize == 0 {
1453 ctx.lock.Lock()
1454 ctx.errors += errors
1455 ctx.lock.Unlock()
1456 return
1457 }
1458
1459 // Publish a batch of messages
1460 for i := 0; i < batchSize; i++ {
1461 subject := fmt.Sprintf("%s.%d", subjectPrefix, fastrand.Uint32n(numSubjects))
1462 if randomData {
1463 fastRandomMutation(messageBuf, 10)
1464 }
1465 _, err := js.Publish(subject, messageBuf)
1466 if err != nil {
1467 errors += 1
1468 }
1469 }
1470 }
1471 }
1472
1473 // Benchmark matrix: (cluster and replicas) * (storage type) * (stream limit)
1474 for _, benchmarkCase := range clusterAndReplicasCases {
1475 b.Run(
1476 fmt.Sprintf(
1477 "N=%d,R=%d",
1478 benchmarkCase.clusterSize,
1479 benchmarkCase.replicas,
1480 ),
1481 func(b *testing.B) {
1482 for _, storageType := range storageTypeCases {
1483 b.Run(
1484 fmt.Sprintf("Storage=%v", storageType),
1485 func(b *testing.B) {
1486
1487 for limitDescription, limitConfigFunc := range limitConfigCases {
1488 b.Run(
1489 limitDescription,
1490 func(b *testing.B) {
1491
1492 // Print benchmark parameters
1493 if verbose {
1494 b.Logf(
1495 "Stream: %+v, Storage: [%v] Limit: [%s], Ops: %d",
1496 benchmarkCase,
1497 storageType,
1498 limitDescription,
1499 b.N,
1500 )
1501 }
1502
1503 // Setup server or cluster
1504 cl, ls, shutdown, nc, js := startJSClusterAndConnect(b, benchmarkCase.clusterSize)
1505 defer shutdown()
1506 defer nc.Close()
1507
1508 // Common stream configuration
1509 streamConfig := &nats.StreamConfig{
1510 Name: "S",
1511 Subjects: []string{fmt.Sprintf("%s.>", subjectPrefix)},
1512 Replicas: benchmarkCase.replicas,
1513 Storage: storageType,
1514 Discard: DiscardOld,
1515 Retention: DiscardOld,
1516 }
1517 // Configure stream limit
1518 limitConfigFunc(streamConfig)
1519
1520 // Create stream
1521 if _, err := js.AddStream(streamConfig); err != nil {
1522 b.Fatalf("Error creating stream: %v", err)
1523 }
1524
1525 // Set up publishers shared context
1526 var pubCtx PublishersContext
1527 pubCtx.readyWg.Add(numPublishers)
1528 pubCtx.completedWg.Add(numPublishers)
1529
1530 // Hold this lock until all publishers are ready
1531 pubCtx.lock.Lock()
1532 pubCtx.messagesLeft = b.N
1533
1534 connectURL := ls.ClientURL()
1535 // If replicated resource, connect to stream leader for lower variability
1536 if benchmarkCase.replicas > 1 {
1537 connectURL = cl.streamLeader("$G", "S").ClientURL()
1538 }
1539
1540 // Spawn publishers routines, each with its own connection and JS context
1541 for i := 0; i < numPublishers; i++ {
1542 nc, err := nats.Connect(connectURL)
1543 if err != nil {
1544 b.Fatal(err)
1545 }
1546 defer nc.Close()
1547 js, err := nc.JetStream()
1548 if err != nil {
1549 b.Fatal(err)
1550 }
1551 go publish(i, &pubCtx, js)
1552 }
1553
1554 // Wait for all publishers to be ready
1555 pubCtx.readyWg.Wait()
1556
1557 // Set size of each operation, for throughput calculation
1558 b.SetBytes(messageSize)
1559
1560 // Benchmark starts here
1561 b.ResetTimer()
1562
1563 // Unblock the publishers
1564 pubCtx.lock.Unlock()
1565
1566 // Wait for all publishers to complete
1567 pubCtx.completedWg.Wait()
1568
1569 // Benchmark ends here
1570 b.StopTimer()
1571
1572 // Sanity check, publishers may have died before completing
1573 if pubCtx.messagesLeft != 0 {
1574 b.Fatalf("Some messages left: %d", pubCtx.messagesLeft)
1575 }
1576
1577 b.ReportMetric(float64(pubCtx.errors)*100/float64(b.N), "%error")
1578 },
1579 )
1580 }
1581 },
1582 )
1583 }
1584 },
1585 )
1586 }
1587 }
1588
1589 func BenchmarkJetStreamKV(b *testing.B) {
1590
1591 const (
1592 verbose = false
1593 kvName = "BUCKET"
1594 keyPrefix = "K_"
1595 seed = 12345
1596 )
1597
1598 runKVGet := func(b *testing.B, kv nats.KeyValue, keys []string) int {
1599 rng := rand.New(rand.NewSource(int64(seed)))
1600 errors := 0
1601
1602 b.ResetTimer()
1603
1604 for i := 1; i <= b.N; i++ {
1605 key := keys[rng.Intn(len(keys))]
1606 _, err := kv.Get(key)
1607 if err != nil {
1608 errors++
1609 continue
1610 }
1611
1612 if verbose && i%1000 == 0 {
1613 b.Logf("Completed %d/%d Get ops", i, b.N)
1614 }
1615 }
1616
1617 b.StopTimer()
1618 return errors
1619 }
1620
1621 runKVPut := func(b *testing.B, kv nats.KeyValue, keys []string, valueSize int) int {
1622
1623 value := make([]byte, valueSize)
1624 rand.New(rand.NewSource(int64(seed))).Read(value)
1625 errors := 0
1626
1627 b.ResetTimer()
1628
1629 for i := 1; i <= b.N; i++ {
1630 key := keys[fastrand.Uint32n(uint32(len(keys)))]
1631 fastRandomMutation(value, 10)
1632 _, err := kv.Put(key, value)
1633 if err != nil {
1634 errors++
1635 continue
1636 }
1637
1638 if verbose && i%1000 == 0 {
1639 b.Logf("Completed %d/%d Put ops", i, b.N)
1640 }
1641 }
1642
1643 b.StopTimer()
1644 return errors
1645 }
1646
1647 runKVUpdate := func(b *testing.B, kv nats.KeyValue, keys []string, valueSize int) int {
1648 value := make([]byte, valueSize)
1649 rand.New(rand.NewSource(int64(seed))).Read(value)
1650 errors := 0
1651
1652 b.ResetTimer()
1653
1654 for i := 1; i <= b.N; i++ {
1655 key := keys[fastrand.Uint32n(uint32(len(keys)))]
1656
1657 kve, getErr := kv.Get(key)
1658 if getErr != nil {
1659 errors++
1660 continue
1661 }
1662
1663 fastRandomMutation(value, 10)
1664 _, updateErr := kv.Update(key, value, kve.Revision())
1665 if updateErr != nil {
1666 errors++
1667 continue
1668 }
1669
1670 if verbose && i%1000 == 0 {
1671 b.Logf("Completed %d/%d Update ops", i, b.N)
1672 }
1673 }
1674
1675 b.StopTimer()
1676 return errors
1677 }
1678
1679 type WorkloadType string
1680 const (
1681 Get WorkloadType = "GET"
1682 Put WorkloadType = "PUT"
1683 Update WorkloadType = "CAS"
1684 )
1685
1686 benchmarksCases := []struct {
1687 clusterSize int
1688 replicas int
1689 numKeys int
1690 valueSize int
1691 }{
1692 {1, 1, 100, 100}, // 1 node with 100 keys, 100B values
1693 {1, 1, 1000, 100}, // 1 node with 1000 keys, 100B values
1694 {3, 3, 100, 100}, // 3 nodes with 100 keys, 100B values
1695 {3, 3, 1000, 100}, // 3 nodes with 1000 keys, 100B values
1696 {3, 3, 1000, 1024}, // 3 nodes with 1000 keys, 1KB values
1697 }
1698
1699 workloadCases := []WorkloadType{
1700 Get,
1701 Put,
1702 Update,
1703 }
1704
1705 for _, bc := range benchmarksCases {
1706
1707 bName := fmt.Sprintf(
1708 "N=%d,R=%d,B=1,K=%d,ValSz=%db",
1709 bc.clusterSize,
1710 bc.replicas,
1711 bc.numKeys,
1712 bc.valueSize,
1713 )
1714
1715 b.Run(
1716 bName,
1717 func(b *testing.B) {
1718 for _, wc := range workloadCases {
1719 wName := fmt.Sprintf("%v", wc)
1720 b.Run(
1721 wName,
1722 func(b *testing.B) {
1723
1724 if verbose {
1725 b.Logf("Running %s workload %s with %d messages", wName, bName, b.N)
1726 }
1727
1728 if verbose {
1729 b.Logf("Setting up %d nodes", bc.clusterSize)
1730 }
1731
1732 // Pre-generate all keys
1733 keys := make([]string, 0, bc.numKeys)
1734 for i := 1; i <= bc.numKeys; i++ {
1735 key := fmt.Sprintf("%s%d", keyPrefix, i)
1736 keys = append(keys, key)
1737 }
1738
1739 // Setup server or cluster
1740 cl, _, shutdown, nc, js := startJSClusterAndConnect(b, bc.clusterSize)
1741 defer shutdown()
1742 defer nc.Close()
1743
1744 // Create bucket
1745 if verbose {
1746 b.Logf("Creating KV %s with R=%d", kvName, bc.replicas)
1747 }
1748 kvConfig := &nats.KeyValueConfig{
1749 Bucket: kvName,
1750 Replicas: bc.replicas,
1751 }
1752 kv, err := js.CreateKeyValue(kvConfig)
1753 if err != nil {
1754 b.Fatalf("Error creating KV: %v", err)
1755 }
1756
1757 // Initialize all keys
1758 rng := rand.New(rand.NewSource(int64(seed)))
1759 value := make([]byte, bc.valueSize)
1760 for _, key := range keys {
1761 rng.Read(value)
1762 _, err := kv.Create(key, value)
1763 if err != nil {
1764 b.Fatalf("Failed to initialize %s/%s: %v", kvName, key, err)
1765 }
1766 }
1767
1768 // If replicated resource, connect to stream leader for lower variability
1769 if bc.replicas > 1 {
1770 nc.Close()
1771 connectURL := cl.streamLeader("$G", fmt.Sprintf("KV_%s", kvName)).ClientURL()
1772 nc, js = jsClientConnectURL(b, connectURL)
1773 defer nc.Close()
1774 }
1775
1776 kv, err = js.KeyValue(kv.Bucket())
1777 if err != nil {
1778 b.Fatalf("Error binding to KV: %v", err)
1779 }
1780
1781 // Set size of each operation, for throughput calculation
1782 b.SetBytes(int64(bc.valueSize))
1783
1784 // Discard time spent during setup
1785 // May reset again further in
1786 b.ResetTimer()
1787
1788 var errors int
1789
1790 switch wc {
1791 case Get:
1792 errors = runKVGet(b, kv, keys)
1793 case Put:
1794 errors = runKVPut(b, kv, keys, bc.valueSize)
1795 case Update:
1796 errors = runKVUpdate(b, kv, keys, bc.valueSize)
1797 default:
1798 b.Fatalf("Unknown workload type: %v", wc)
1799 }
1800
1801 // Benchmark ends here, (may have stopped earlier)
1802 b.StopTimer()
1803
1804 b.ReportMetric(float64(errors)*100/float64(b.N), "%error")
1805 },
1806 )
1807 }
1808 },
1809 )
1810 }
1811 }
1812
1813 func BenchmarkJetStreamObjStore(b *testing.B) {
1814 const (
1815 verbose = false
1816 objStoreName = "B"
1817 keyPrefix = "K_"
1818 seed = 12345
1819 initKeys = true
1820
1821 // read/write ratios
1822 ReadOnly = 1.0
1823 WriteOnly = 0.0
1824 )
1825
1826 // rwRatio to string
1827 rwRatioToString := func(rwRatio float64) string {
1828 switch rwRatio {
1829 case ReadOnly:
1830 return "readOnly"
1831 case WriteOnly:
1832 return "writeOnly"
1833 default:
1834 return fmt.Sprintf("%0.1f", rwRatio)
1835 }
1836 }
1837
1838 // benchmark for object store by performing read/write operations with data of random size
1839 RunObjStoreBenchmark := func(b *testing.B, objStore nats.ObjectStore, minObjSz int, maxObjSz int, numKeys int, rwRatio float64) (int, int, int) {
1840 var (
1841 errors int
1842 reads int
1843 writes int
1844 )
1845
1846 dataBuf := make([]byte, maxObjSz)
1847 rng := rand.New(rand.NewSource(int64(seed)))
1848 rng.Read(dataBuf)
1849
1850 // Each operation is processing a random amount of bytes within a size range which
1851 // will be either read from or written to an object store bucket. However, here we are
1852 // approximating the size of the processed data with a simple average of the range.
1853 b.SetBytes(int64((minObjSz + maxObjSz) / 2))
1854
1855 for i := 1; i <= b.N; i++ {
1856 key := fmt.Sprintf("%s_%d", keyPrefix, rng.Intn(numKeys))
1857 var err error
1858
1859 rwOp := rng.Float64()
1860 switch {
1861 case rwOp <= rwRatio:
1862 // Read Op
1863 _, err = objStore.GetBytes(key)
1864 reads++
1865 case rwOp > rwRatio:
1866 // Write Op
1867 // dataSz is a random value between min-max object size and cannot be less than 1 byte
1868 dataSz := rng.Intn(maxObjSz-minObjSz+1) + minObjSz
1869 data := dataBuf[:dataSz]
1870 fastRandomMutation(data, 10)
1871 _, err = objStore.PutBytes(key, data)
1872 writes++
1873 }
1874 if err != nil {
1875 errors++
1876 }
1877
1878 if verbose && i%1000 == 0 {
1879 b.Logf("Completed: %d reads, %d writes, %d errors. %d/%d total operations have been completed.", reads, writes, errors, i, b.N)
1880 }
1881 }
1882 return errors, reads, writes
1883 }
1884
1885 // benchmark cases table
1886 benchmarkCases := []struct {
1887 storage nats.StorageType
1888 numKeys int
1889 minObjSz int
1890 maxObjSz int
1891 }{
1892 {nats.MemoryStorage, 100, 1024, 102400}, // mem storage, 100 objects sized (1KB-100KB)
1893 {nats.MemoryStorage, 100, 102400, 1048576}, // mem storage, 100 objects sized (100KB-1MB)
1894 {nats.MemoryStorage, 1000, 10240, 102400}, // mem storage, 1k objects of various size (10KB - 100KB)
1895 {nats.FileStorage, 100, 1024, 102400}, // file storage, 100 objects sized (1KB-100KB)
1896 {nats.FileStorage, 1000, 10240, 1048576}, // file storage, 1k objects of various size (10KB - 1MB)
1897 {nats.FileStorage, 100, 102400, 1048576}, // file storage, 100 objects sized (100KB-1MB)
1898 {nats.FileStorage, 100, 1048576, 10485760}, // file storage, 100 objects sized (1MB-10MB)
1899 {nats.FileStorage, 10, 10485760, 104857600}, // file storage, 10 objects sized (10MB-100MB)
1900 }
1901
1902 var (
1903 clusterSizeCases = []int{1, 3}
1904 rwRatioCases = []float64{ReadOnly, WriteOnly, 0.8}
1905 )
1906
1907 // Test with either single node or 3 node cluster
1908 for _, clusterSize := range clusterSizeCases {
1909 replicas := clusterSize
1910 cName := fmt.Sprintf("N=%d,R=%d", clusterSize, replicas)
1911 b.Run(
1912 cName,
1913 func(b *testing.B) {
1914 for _, rwRatio := range rwRatioCases {
1915 rName := fmt.Sprintf("workload=%s", rwRatioToString(rwRatio))
1916 b.Run(
1917 rName,
1918 func(b *testing.B) {
1919 // Test all tabled benchmark cases
1920 for _, bc := range benchmarkCases {
1921 bName := fmt.Sprintf("K=%d,storage=%s,minObjSz=%db,maxObjSz=%db", bc.numKeys, bc.storage, bc.minObjSz, bc.maxObjSz)
1922 b.Run(
1923 bName,
1924 func(b *testing.B) {
1925
1926 // Test setup
1927 rng := rand.New(rand.NewSource(int64(seed)))
1928
1929 if verbose {
1930 b.Logf("Setting up %d nodes", replicas)
1931 }
1932
1933 // Setup server or cluster
1934 cl, _, shutdown, nc, js := startJSClusterAndConnect(b, clusterSize)
1935 defer shutdown()
1936 defer nc.Close()
1937
1938 // Initialize object store
1939 if verbose {
1940 b.Logf("Creating ObjectStore %s with R=%d", objStoreName, replicas)
1941 }
1942 objStoreConfig := &nats.ObjectStoreConfig{
1943 Bucket: objStoreName,
1944 Replicas: replicas,
1945 Storage: bc.storage,
1946 }
1947 objStore, err := js.CreateObjectStore(objStoreConfig)
1948 if err != nil {
1949 b.Fatalf("Error creating ObjectStore: %v", err)
1950 }
1951
1952 // If replicated resource, connect to stream leader for lower variability
1953 if clusterSize > 1 {
1954 nc.Close()
1955 connectURL := cl.streamLeader("$G", fmt.Sprintf("OBJ_%s", objStoreName)).ClientURL()
1956 nc, js := jsClientConnectURL(b, connectURL)
1957 defer nc.Close()
1958 objStore, err = js.ObjectStore(objStoreName)
1959 if err != nil {
1960 b.Fatalf("Error binding to ObjectStore: %v", err)
1961 }
1962 }
1963
1964 // Initialize keys
1965 if initKeys {
1966 for n := 0; n < bc.numKeys; n++ {
1967 key := fmt.Sprintf("%s_%d", keyPrefix, n)
1968 dataSz := rng.Intn(bc.maxObjSz-bc.minObjSz+1) + bc.minObjSz
1969 value := make([]byte, dataSz)
1970 rng.Read(value)
1971 _, err := objStore.PutBytes(key, value)
1972 if err != nil {
1973 b.Fatalf("Failed to initialize %s/%s: %v", objStoreName, key, err)
1974 }
1975 }
1976 }
1977
1978 b.ResetTimer()
1979
1980 // Run benchmark
1981 errors, reads, writes := RunObjStoreBenchmark(b, objStore, bc.minObjSz, bc.maxObjSz, bc.numKeys, rwRatio)
1982
1983 // Report metrics
1984 b.ReportMetric(float64(errors)*100/float64(b.N), "%error")
1985 b.ReportMetric(float64(reads), "reads")
1986 b.ReportMetric(float64(writes), "writes")
1987
1988 },
1989 )
1990 }
1991 },
1992 )
1993 }
1994 },
1995 )
1996 }
1997 }
1998
1999 func BenchmarkJetStreamPublishConcurrent(b *testing.B) {
2000 const (
2001 subject = "test-subject"
2002 streamName = "test-stream"
2003 )
2004
2005 type BenchPublisher struct {
2006 // nats connection for this publisher
2007 conn *nats.Conn
2008 // jetstream context
2009 js nats.JetStreamContext
2010 // message buffer
2011 messageData []byte
2012 // number of publish calls
2013 publishCalls int
2014 // number of publish errors
2015 publishErrors int
2016 }
2017
2018 messageSizeCases := []int64{
2019 10, // 10B
2020 1024, // 1KiB
2021 102400, // 100KiB
2022 }
2023 numPubsCases := []int{
2024 12,
2025 }
2026
2027 replicasCases := []struct {
2028 clusterSize int
2029 replicas int
2030 }{
2031 {1, 1},
2032 {3, 3},
2033 {3, 3},
2034 }
2035
2036 workload := func(b *testing.B, numPubs int, messageSize int64, clientUrl string) {
2037
2038 // create N publishers
2039 publishers := make([]BenchPublisher, numPubs)
2040 for i := range publishers {
2041 // create publisher connection and jetstream context
2042 ncPub, err := nats.Connect(clientUrl)
2043 if err != nil {
2044 b.Fatal(err)
2045 }
2046 defer ncPub.Close()
2047 jsPub, err := ncPub.JetStream()
2048 if err != nil {
2049 b.Fatal(err)
2050 }
2051
2052 // initialize publisher
2053 publishers[i] = BenchPublisher{
2054 conn: ncPub,
2055 js: jsPub,
2056 messageData: make([]byte, messageSize),
2057 publishCalls: 0,
2058 publishErrors: 0,
2059 }
2060 rand.New(rand.NewSource(int64(i))).Read(publishers[i].messageData)
2061 }
2062
2063 // waits for all publishers sub-routines and for main thread to be ready
2064 var workloadReadyWg sync.WaitGroup
2065 workloadReadyWg.Add(1 + numPubs)
2066
2067 // wait group blocks main thread until publish workload is completed, it is decremented after stream receives b.N messages from all publishers
2068 var benchCompleteWg sync.WaitGroup
2069 benchCompleteWg.Add(1)
2070
2071 // wait group to ensure all publishers have been torn down
2072 var finishedPublishersWg sync.WaitGroup
2073 finishedPublishersWg.Add(numPubs)
2074
2075 // start go routines for all publishers, wait till all publishers are initialized before starting publish workload
2076 for i := range publishers {
2077
2078 go func(pubId int) {
2079 // signal that this publisher has been torn down
2080 defer finishedPublishersWg.Done()
2081
2082 // publisher sub-routine is ready
2083 workloadReadyWg.Done()
2084
2085 // start workload when main thread and all other publishers are ready
2086 workloadReadyWg.Wait()
2087
2088 // publish until stream receives b.N messages
2089 for {
2090 // random bytes as payload
2091 fastRandomMutation(publishers[pubId].messageData, 10)
2092 // attempt to publish message
2093 pubAck, err := publishers[pubId].js.Publish(subject, publishers[pubId].messageData)
2094 publishers[pubId].publishCalls += 1
2095 if err != nil {
2096 publishers[pubId].publishErrors += 1
2097 continue
2098 }
2099 // all messages have been published to stream
2100 if pubAck.Sequence == uint64(b.N) {
2101 benchCompleteWg.Done()
2102 }
2103 // a publisher has already published b.N messages, stop publishing
2104 if pubAck.Sequence >= uint64(b.N) {
2105 return
2106 }
2107 }
2108 }(i)
2109 }
2110
2111 // set bytes per operation
2112 b.SetBytes(messageSize)
2113
2114 // main thread is ready
2115 workloadReadyWg.Done()
2116 // start the clock
2117 b.ResetTimer()
2118
2119 // wait till termination cond reached
2120 benchCompleteWg.Wait()
2121 // stop the clock
2122 b.StopTimer()
2123
2124 // wait for all publishers to shutdown
2125 finishedPublishersWg.Wait()
2126
2127 // sum up publish calls and errors
2128 publishCalls := 0
2129 publishErrors := 0
2130 for _, pub := range publishers {
2131 publishCalls += pub.publishCalls
2132 publishErrors += pub.publishErrors
2133 }
2134
2135 // report error rate
2136 errorRate := 100 * float64(publishErrors) / float64(publishCalls)
2137 b.ReportMetric(errorRate, "%error")
2138 }
2139
2140 // benchmark case matrix
2141 for _, replicasCase := range replicasCases {
2142 title := fmt.Sprintf("N=%d,R=%d", replicasCase.clusterSize, replicasCase.replicas)
2143 b.Run(
2144 title,
2145 func(b *testing.B) {
2146 for _, messageSize := range messageSizeCases {
2147 b.Run(
2148 fmt.Sprintf("msgSz=%db", messageSize),
2149 func(b *testing.B) {
2150 for _, numPubs := range numPubsCases {
2151 b.Run(
2152 fmt.Sprintf("pubs=%d", numPubs),
2153 func(b *testing.B) {
2154
2155 // start jetstream cluster
2156 cl, ls, shutdown, nc, js := startJSClusterAndConnect(b, replicasCase.clusterSize)
2157 defer shutdown()
2158 defer nc.Close()
2159 clientUrl := ls.ClientURL()
2160
2161 // create stream
2162 _, err := jsStreamCreate(b, nc, &StreamConfig{
2163 Name: streamName,
2164 Subjects: []string{subject},
2165 Replicas: replicasCase.replicas,
2166 Storage: FileStorage,
2167 })
2168 if err != nil {
2169 b.Fatal(err)
2170 }
2171 defer js.DeleteStream(streamName)
2172
2173 // If replicated resource, connect to stream leader for lower variability
2174 if replicasCase.replicas > 1 {
2175 nc.Close()
2176 clientUrl = cl.streamLeader("$G", streamName).ClientURL()
2177 nc, _ = jsClientConnectURL(b, clientUrl)
2178 defer nc.Close()
2179 }
2180
2181 // run workload
2182 workload(b, numPubs, messageSize, clientUrl)
2183 },
2184 )
2185 }
2186 })
2187 }
2188 })
2189 }
2190 }
2191
2192 func BenchmarkJetStreamParallelStartup(b *testing.B) {
2193 omp := runtime.GOMAXPROCS(-1)
2194 streams, msgs, cardinality := omp, 100_000, 10_000
2195
2196 _, s, shutdown, nc, js := startJSClusterAndConnect(b, 1)
2197 defer shutdown()
2198 jsc := *s.JetStreamConfig()
2199 sd := strings.TrimSuffix(jsc.StoreDir, "/jetstream")
2200
2201 b.Logf("Building %d streams with %d messages, %d subjects...", streams, msgs, cardinality)
2202 start := time.Now()
2203 for i := range streams {
2204 jsStreamCreate(b, nc, &StreamConfig{
2205 Name: fmt.Sprintf("stream_%d", i),
2206 Subjects: []string{fmt.Sprintf("%d.>", i)},
2207 Storage: FileStorage,
2208 })
2209 for n := range msgs {
2210 subj := fmt.Sprintf("%d.%d", i, n%cardinality)
2211 _, err := js.Publish(subj, nil)
2212 require_NoError(b, err)
2213 }
2214 }
2215 b.Logf("Streams built in %s", time.Since(start))
2216
2217 bench := func(b *testing.B) {
2218 s.shutdownJetStream()
2219 jsc.StoreDir = sd
2220 require_NoError(b, filepath.Walk(jsc.StoreDir, func(path string, info os.FileInfo, err error) error {
2221 require_NoError(b, err)
2222 if info.Mode().IsRegular() && info.Name() == "index.db" {
2223 return os.Truncate(path, 0)
2224 }
2225 return nil
2226 }))
2227 b.ResetTimer()
2228 s.EnableJetStream(&jsc)
2229 }
2230
2231 // Try to step down GOMAXPROCS in common CPU core counts.
2232 mp := 1 << (bits.Len(uint(omp)) - 1)
2233 if omp > mp {
2234 b.Run(fmt.Sprintf("GOMAXPROCS=%d", omp), func(b *testing.B) {
2235 bench(b)
2236 })
2237 }
2238 for ; mp >= 1; mp >>= 1 {
2239 b.Run(fmt.Sprintf("GOMAXPROCS=%d", mp), func(b *testing.B) {
2240 runtime.GOMAXPROCS(mp)
2241 defer runtime.GOMAXPROCS(omp)
2242 bench(b)
2243 })
2244 }
2245 }
2246
2247 func BenchmarkJetStreamScanForSources(b *testing.B) {
2248 _, s, shutdown, nc, js := startJSClusterAndConnect(b, 1)
2249 defer shutdown()
2250
2251 jsStreamCreate(b, nc, &StreamConfig{
2252 Name: "origin",
2253 Subjects: []string{"foo"},
2254 Storage: FileStorage,
2255 })
2256
2257 jsStreamCreate(b, nc, &StreamConfig{
2258 Name: "stream",
2259 Subjects: []string{"bar"},
2260 Storage: FileStorage,
2261 Sources: []*StreamSource{
2262 {
2263 Name: "origin",
2264 FilterSubject: "foo",
2265 },
2266 },
2267 })
2268
2269 // Start by publishing some messages to the sourcing stream.
2270 for range 1000 {
2271 _, err := js.Publish("bar", nil)
2272 require_NoError(b, err)
2273 }
2274
2275 // Then publish a message to the origin stream.
2276 _, err := js.Publish("foo", nil)
2277 require_NoError(b, err)
2278
2279 // Wait for the sourced message from the origin stream.
2280 checkFor(b, 5*time.Second, 100*time.Millisecond, func() error {
2281 si, err := js.StreamInfo("stream")
2282 if err != nil {
2283 return err
2284 }
2285 if si.State.Msgs != 1001 {
2286 return fmt.Errorf("waiting for sourcing")
2287 }
2288 return nil
2289 })
2290
2291 // Now publish a LOT more messages to the sourcing stream
2292 // which previously the reverse scan would have had to scan
2293 // over linearly.
2294 for range 100_000 {
2295 _, err := js.Publish("bar", nil)
2296 require_NoError(b, err)
2297 }
2298
2299 mset, err := s.globalAccount().lookupStream("stream")
2300 require_NoError(b, err)
2301
2302 b.Run("StartingSequenceForSources", func(b *testing.B) {
2303 mset.startingSequenceForSources()
2304 })
2305 }
2306
2307 // Helper function to stand up a JS-enabled single server or cluster
2308 func startJSClusterAndConnect(b *testing.B, clusterSize int) (c *cluster, s *Server, shutdown func(), nc *nats.Conn, js nats.JetStreamContext) {
2309 b.Helper()
2310 var err error
2311
2312 if clusterSize == 1 {
2313 s = RunBasicJetStreamServer(b)
2314 shutdown = func() {
2315 s.Shutdown()
2316 }
2317 s.optsMu.Lock()
2318 s.opts.SyncInterval = 5 * time.Minute
2319 s.optsMu.Unlock()
2320 } else {
2321 c = createJetStreamClusterExplicit(b, "BENCH_PUB", clusterSize)
2322 c.waitOnClusterReadyWithNumPeers(clusterSize)
2323 c.waitOnLeader()
2324 s = c.leader()
2325 shutdown = func() {
2326 c.shutdown()
2327 }
2328 for _, s := range c.servers {
2329 s.optsMu.Lock()
2330 s.opts.SyncInterval = 5 * time.Minute
2331 s.optsMu.Unlock()
2332 }
2333 }
2334
2335 nc, err = nats.Connect(s.ClientURL())
2336 if err != nil {
2337 b.Fatalf("failed to connect: %s", err)
2338 }
2339
2340 js, err = nc.JetStream()
2341 if err != nil {
2342 b.Fatalf("failed to init jetstream: %s", err)
2343 }
2344
2345 return c, s, shutdown, nc, js
2346 }
2347
2348 // BenchmarkJetStreamDirectGet measures direct get latency, single and multi,
2349 // idle and while a concurrent writer floods the stream, plus the publish path
2350 // on its own to spot read-isolation cost on writes.
2351 func BenchmarkJetStreamDirectGet(b *testing.B) {
2352 const numSubjects = 256
2353
2354 setup := func(b *testing.B) (*Server, *nats.Conn) {
2355 b.Helper()
2356 s := RunBasicJetStreamServer(b)
2357 nc, js := jsClientConnect(b, s)
2358 _, err := js.AddStream(&nats.StreamConfig{
2359 Name: "TEST",
2360 Subjects: []string{"foo.*"},
2361 Storage: nats.FileStorage,
2362 MaxMsgsPerSubject: 1,
2363 AllowDirect: true,
2364 })
2365 if err != nil {
2366 b.Fatalf("add stream: %v", err)
2367 }
2368 payload := make([]byte, 64)
2369 for i := 0; i < numSubjects; i++ {
2370 if _, err := js.PublishAsync(fmt.Sprintf("foo.%d", i), payload); err != nil {
2371 b.Fatalf("preload: %v", err)
2372 }
2373 }
2374 select {
2375 case <-js.PublishAsyncComplete():
2376 case <-time.After(10 * time.Second):
2377 b.Fatalf("preload did not complete")
2378 }
2379 return s, nc
2380 }
2381
2382 // Hammer the stream with async publishes over the same subject space for
2383 // the duration of the benchmark. The stop func reports publishes acked.
2384 startWriter := func(b *testing.B, s *Server) (stop func() uint64) {
2385 b.Helper()
2386 nc, js := jsClientConnect(b, s, nats.NoEcho())
2387 done := make(chan struct{})
2388 finished := make(chan struct{})
2389 var acked atomic.Uint64
2390 go func() {
2391 defer close(finished)
2392 payload := make([]byte, 64)
2393 for i := 0; ; i++ {
2394 select {
2395 case <-done:
2396 return
2397 default:
2398 }
2399 pa, err := js.PublishAsync(fmt.Sprintf("foo.%d", i%numSubjects), payload)
2400 if err != nil {
2401 // Pending limit reached, wait for completions.
2402 select {
2403 case <-js.PublishAsyncComplete():
2404 case <-time.After(time.Second):
2405 }
2406 continue
2407 }
2408 go func() {
2409 select {
2410 case <-pa.Ok():
2411 acked.Add(1)
2412 case <-pa.Err():
2413 case <-done:
2414 }
2415 }()
2416 }
2417 }()
2418 return func() uint64 {
2419 close(done)
2420 <-finished
2421 nc.Close()
2422 return acked.Load()
2423 }
2424 }
2425
2426 single := `{"last_by_subj":"foo.7"}`
2427 multi := `{"multi_last":["foo.7","foo.11","foo.13","foo.17","foo.19","foo.23","foo.29","foo.31"]}`
2428 for _, bc := range []struct {
2429 name string
2430 req string
2431 withWrites bool
2432 }{
2433 {"Single/Idle", single, false},
2434 {"Single/UnderWrites", single, true},
2435 {"Multi/Idle", multi, false},
2436 {"Multi/UnderWrites", multi, true},
2437 } {
2438 b.Run(bc.name, func(b *testing.B) {
2439 s, nc := setup(b)
2440 defer s.Shutdown()
2441 defer nc.Close()
2442
2443 var stop func() uint64
2444 if bc.withWrites {
2445 stop = startWriter(b, s)
2446 // Let the writer get going.
2447 time.Sleep(100 * time.Millisecond)
2448 }
2449
2450 getSubj := fmt.Sprintf(JSDirectMsgGetT, "TEST")
2451 req := []byte(bc.req)
2452 b.ResetTimer()
2453 for i := 0; i < b.N; i++ {
2454 if _, err := nc.Request(getSubj, req, 5*time.Second); err != nil {
2455 b.Fatalf("direct get: %v", err)
2456 }
2457 }
2458 b.StopTimer()
2459 if stop != nil {
2460 writes := stop()
2461 b.ReportMetric(float64(writes)/b.Elapsed().Seconds(), "writes/s")
2462 }
2463 })
2464 }
2465
2466 b.Run("PublishOnly", func(b *testing.B) {
2467 s, nc := setup(b)
2468 defer s.Shutdown()
2469 defer nc.Close()
2470
2471 _, js := jsClientConnect(b, s)
2472 payload := make([]byte, 64)
2473 b.ResetTimer()
2474 for i := 0; i < b.N; i++ {
2475 if _, err := js.PublishAsync(fmt.Sprintf("foo.%d", i%numSubjects), payload); err != nil {
2476 i--
2477 select {
2478 case <-js.PublishAsyncComplete():
2479 case <-time.After(time.Second):
2480 }
2481 }
2482 }
2483 select {
2484 case <-js.PublishAsyncComplete():
2485 case <-time.After(30 * time.Second):
2486 b.Fatalf("publishes did not complete")
2487 }
2488 })
2489 }