Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce allocations in consumers #6039

Merged
merged 3 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion server/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3126,6 +3126,14 @@ func (o *consumer) needAck(sseq uint64, subj string) bool {
return needAck
}

// Used in nextReqFromMsg, since the json.Unmarshal causes the request
// struct to escape to the heap always. This should reduce GC pressure.
var jsGetNextPool = sync.Pool{
New: func() any {
return &JSApiConsumerGetNextRequest{}
},
}

// Helper for the next message requests.
func nextReqFromMsg(msg []byte) (time.Time, int, int, bool, time.Duration, time.Time, error) {
req := bytes.TrimSpace(msg)
Expand All @@ -3135,7 +3143,11 @@ func nextReqFromMsg(msg []byte) (time.Time, int, int, bool, time.Duration, time.
return time.Time{}, 1, 0, false, 0, time.Time{}, nil

case req[0] == '{':
var cr JSApiConsumerGetNextRequest
cr := jsGetNextPool.Get().(*JSApiConsumerGetNextRequest)
defer func() {
*cr = JSApiConsumerGetNextRequest{}
jsGetNextPool.Put(cr)
derekcollison marked this conversation as resolved.
Show resolved Hide resolved
}()
if err := json.Unmarshal(req, &cr); err != nil {
return time.Time{}, -1, 0, false, 0, time.Time{}, err
}
Expand Down Expand Up @@ -3535,6 +3547,7 @@ func (o *consumer) processNextMsgRequest(reply string, msg []byte) {

if err := o.waiting.add(wr); err != nil {
sendErr(409, "Exceeded MaxWaiting")
wr.recycle()
return
}
o.signalNewMessages()
Expand Down
6 changes: 6 additions & 0 deletions server/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -5199,6 +5199,9 @@ func newJSPubMsg(dsubj, subj, reply string, hdr, msg []byte, o *consumer, seq ui
if pm != nil {
m = pm.(*jsPubMsg)
buf = m.buf[:0]
if hdr != nil {
hdr = append(m.hdr[:0], hdr...)
}
} else {
m = new(jsPubMsg)
}
Expand Down Expand Up @@ -5227,6 +5230,9 @@ func (pm *jsPubMsg) returnToPool() {
if len(pm.buf) > 0 {
pm.buf = pm.buf[:0]
}
if len(pm.hdr) > 0 {
pm.hdr = pm.hdr[:0]
}
jsPubMsgPool.Put(pm)
}

Expand Down