perf(logs): filter log events by time before sorting (#4474)

GetLogEvents and FilterLogEvents sorted every stored event in the
stream or group before applying the startTime/endTime (and, for
FilterLogEvents, the filter pattern) window. Apply the cheap per-event
filters first so only the events that survive the window get sorted;
results, ordering, and pagination tokens are unchanged.
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-28 01:04:56 -04:00
1 parent c7492ce0f4
commit bf47dd7193
2 files changed
+85 -3

No files matched your search

@@ -788,11 +788,13 @@ public class CloudWatchLogsService implements ResourceProvider {
String eventPrefix = eventKeyPrefix(region, groupName, streamName);
List<LogEvent> all = eventStore.scan(k -> k.startsWith(eventPrefix));
all.sort(EVENT_ORDER);
// Filter before sorting so a narrow time window only pays the comparison cost for
// the events it keeps, instead of sorting the whole stream and discarding most of it.
List<LogEvent> filtered = all.stream()
.filter(e -> (startTime == null || e.getTimestamp() >= startTime)
&& (endTime == null || e.getTimestamp() <= endTime))
.sorted(EVENT_ORDER)
.toList();
int total = filtered.size();
@@ -872,13 +874,14 @@ public class CloudWatchLogsService implements ResourceProvider {
eventStore.get(key).ifPresent(e -> all.add(new FilteredEvent(streamName, e)));
}
all.sort(Comparator.comparing(FilteredEvent::event, EVENT_ORDER));
// Filter before sorting so a narrow time window or pattern only pays the comparison
// cost for the events it keeps, instead of sorting every stored event up front.
List<FilteredEvent> matches = all.stream()
.filter(f -> (startTime == null || f.event().getTimestamp() >= startTime)
&& (endTime == null || f.event().getTimestamp() <= endTime))
.filter(f -> filterPattern == null || filterPattern.isBlank()
|| f.event().getMessage().contains(filterPattern))
.sorted(Comparator.comparing(FilteredEvent::event, EVENT_ORDER))
.toList();
// The cursor indexes matches rather than stored events, which is why the window is applied