Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

perf: Optimize WebSocket data payloads and push frequency by implementing conditional fetching and client-side push interval control, and improve GeoIP lookup efficiency through batching.

luolei2bdb8359debf
diff --git a/apps/collector/src/collector.ts b/apps/collector/src/collector.ts
index ec410b8..2d18e83 100644
--- a/apps/collector/src/collector.ts
+++ b/apps/collector/src/collector.ts
@@ -367,6 +367,10 @@ export function createCollector(
data.connections.map((c) => c?.id).filter(Boolean),
);
let hasNewTraffic = false;
+ const geoBatchByIp = new Map<
+ string,
+ { upload: number; download: number; connections: number }
+ >();
// Process all current connections
for (const conn of data.connections) {
@@ -437,32 +441,17 @@ export function createCollector(
now
);
- // Queue GeoIP lookup
+ // Aggregate GeoIP lookup payload by destination IP per batch.
if (geoService && ip) {
- geoService
- .getGeoLocation(ip)
- .then((geo) => {
- if (geo) {
- batchBuffer.addGeoResult({
- ip,
- geo,
- upload: conn.upload,
- download: conn.download,
- timestampMs: now,
- });
- realtimeStore.recordCountryTraffic(
- id,
- geo,
- conn.upload,
- conn.download,
- 1,
- now,
- );
- }
- })
- .catch(() => {
- // Silently fail for GeoIP errors
- });
+ const existingGeo = geoBatchByIp.get(ip) || {
+ upload: 0,
+ download: 0,
+ connections: 0,
+ };
+ existingGeo.upload += conn.upload;
+ existingGeo.download += conn.download;
+ existingGeo.connections += 1;
+ geoBatchByIp.set(ip, existingGeo);
}
hasNewTraffic = true;
@@ -509,32 +498,17 @@ export function createCollector(
now
);
- // Queue GeoIP lookup for delta
+ // Aggregate GeoIP lookup payload by destination IP per batch.
if (geoService && existing.ip) {
- geoService
- .getGeoLocation(existing.ip)
- .then((geo) => {
- if (geo) {
- batchBuffer.addGeoResult({
- ip: existing.ip,
- geo,
- upload: uploadDelta,
- download: downloadDelta,
- timestampMs: now,
- });
- realtimeStore.recordCountryTraffic(
- id,
- geo,
- uploadDelta,
- downloadDelta,
- 1,
- now,
- );
- }
- })
- .catch(() => {
- // Silently fail for GeoIP errors
- });
+ const existingGeo = geoBatchByIp.get(existing.ip) || {
+ upload: 0,
+ download: 0,
+ connections: 0,
+ };
+ existingGeo.upload += uploadDelta;
+ existingGeo.download += downloadDelta;
+ existingGeo.connections += 1;
+ geoBatchByIp.set(existing.ip, existingGeo);
}
existing.lastUpload = conn.upload;
@@ -552,6 +526,35 @@ export function createCollector(
}
}
+ if (geoService && geoBatchByIp.size > 0) {
+ for (const [ip, traffic] of geoBatchByIp) {
+ geoService
+ .getGeoLocation(ip)
+ .then((geo) => {
+ if (geo) {
+ batchBuffer.addGeoResult({
+ ip,
+ geo,
+ upload: traffic.upload,
+ download: traffic.download,
+ timestampMs: now,
+ });
+ realtimeStore.recordCountryTraffic(
+ id,
+ geo,
+ traffic.upload,
+ traffic.download,
+ traffic.connections,
+ now,
+ );
+ }
+ })
+ .catch(() => {
+ // Silently fail for GeoIP errors
+ });
+ }
+ }
+
if (batchBuffer.size() >= FLUSH_MAX_BUFFER_SIZE) {
flushBatch();
}
diff --git a/apps/collector/src/websocket.ts b/apps/collector/src/websocket.ts
index e2afffe..c40dbb3 100644
--- a/apps/collector/src/websocket.ts
+++ b/apps/collector/src/websocket.ts
@@ -610,37 +610,81 @@ export class StatsWebSocketServer {
}
const includeRealtime = this.shouldIncludeRealtime(range);
+ const wantsFullSummary =
+ !trend &&
+ !deviceDetail &&
+ !proxyDetail &&
+ !ruleDetail &&
+ !includeRuleChainFlow &&
+ !domainsPage &&
+ !ipsPage;
+
+ const summary = wantsFullSummary
+ ? this.db.getSummary(resolvedBackendId, range.start, range.end)
+ : {
+ totalUpload: 0,
+ totalDownload: 0,
+ totalConnections: 0,
+ uniqueDomains: 0,
+ uniqueIPs: 0,
+ };
+
+ const dbTopDomains = wantsFullSummary
+ ? this.db.getTopDomains(resolvedBackendId, 100, range.start, range.end)
+ : undefined;
+ const topDomains = wantsFullSummary && dbTopDomains
+ ? includeRealtime
+ ? realtimeStore.mergeTopDomains(resolvedBackendId, dbTopDomains, 100)
+ : dbTopDomains
+ : [];
- const summary = this.db.getSummary(resolvedBackendId, range.start, range.end);
-
- const dbTopDomains = this.db.getTopDomains(resolvedBackendId, 100, range.start, range.end);
- const topDomains = includeRealtime
- ? realtimeStore.mergeTopDomains(resolvedBackendId, dbTopDomains, 100)
- : dbTopDomains;
-
- const dbTopIPs = this.db.getTopIPs(resolvedBackendId, 100, range.start, range.end);
- const topIPs = includeRealtime
- ? realtimeStore.mergeTopIPs(resolvedBackendId, dbTopIPs, 100)
- : dbTopIPs;
-
- const dbProxyStats = this.db.getProxyStats(resolvedBackendId, range.start, range.end);
- const proxyStats = includeRealtime
- ? realtimeStore.mergeProxyStats(resolvedBackendId, dbProxyStats)
- : dbProxyStats;
- const dbCountryStats = this.db.getCountryStats(resolvedBackendId, 50, range.start, range.end);
- const countryStats = includeRealtime
- ? realtimeStore.mergeCountryStats(resolvedBackendId, dbCountryStats)
- : dbCountryStats;
- const dbDeviceStats = this.db.getDevices(resolvedBackendId, 50, range.start, range.end);
- const deviceStats = includeRealtime
- ? realtimeStore.mergeDeviceStats(resolvedBackendId, dbDeviceStats, 50)
- : dbDeviceStats;
-
- const dbRuleStats = this.db.getRuleStats(resolvedBackendId, range.start, range.end);
- const ruleStats = includeRealtime
- ? realtimeStore.mergeRuleStats(resolvedBackendId, dbRuleStats)
- : dbRuleStats;
- const hourlyStats = this.db.getHourlyStats(resolvedBackendId, 24, range.start, range.end);
+ const dbTopIPs = wantsFullSummary
+ ? this.db.getTopIPs(resolvedBackendId, 100, range.start, range.end)
+ : undefined;
+ const topIPs = wantsFullSummary && dbTopIPs
+ ? includeRealtime
+ ? realtimeStore.mergeTopIPs(resolvedBackendId, dbTopIPs, 100)
+ : dbTopIPs
+ : [];
+
+ const dbProxyStats = wantsFullSummary
+ ? this.db.getProxyStats(resolvedBackendId, range.start, range.end)
+ : undefined;
+ const proxyStats = wantsFullSummary && dbProxyStats
+ ? includeRealtime
+ ? realtimeStore.mergeProxyStats(resolvedBackendId, dbProxyStats)
+ : dbProxyStats
+ : [];
+
+ const dbCountryStats = wantsFullSummary
+ ? this.db.getCountryStats(resolvedBackendId, 50, range.start, range.end)
+ : undefined;
+ const countryStats = wantsFullSummary && dbCountryStats
+ ? includeRealtime
+ ? realtimeStore.mergeCountryStats(resolvedBackendId, dbCountryStats)
+ : dbCountryStats
+ : undefined;
+
+ const dbDeviceStats = wantsFullSummary
+ ? this.db.getDevices(resolvedBackendId, 50, range.start, range.end)
+ : undefined;
+ const deviceStats = wantsFullSummary && dbDeviceStats
+ ? includeRealtime
+ ? realtimeStore.mergeDeviceStats(resolvedBackendId, dbDeviceStats, 50)
+ : dbDeviceStats
+ : undefined;
+
+ const dbRuleStats = wantsFullSummary
+ ? this.db.getRuleStats(resolvedBackendId, range.start, range.end)
+ : undefined;
+ const ruleStats = wantsFullSummary && dbRuleStats
+ ? includeRealtime
+ ? realtimeStore.mergeRuleStats(resolvedBackendId, dbRuleStats)
+ : dbRuleStats
+ : undefined;
+ const hourlyStats = wantsFullSummary
+ ? this.db.getHourlyStats(resolvedBackendId, 24, range.start, range.end)
+ : [];
const trendStats = trend
? this.db.getTrafficTrendAggregated(
resolvedBackendId,
@@ -819,7 +863,7 @@ export class StatsWebSocketServer {
totalDomains: summary.uniqueDomains,
totalIPs: summary.uniqueIPs,
totalProxies: proxyStats.length,
- totalRules: ruleStats.length,
+ totalRules: ruleStats?.length,
topDomains,
topIPs,
proxyStats,
@@ -844,7 +888,7 @@ export class StatsWebSocketServer {
hourlyStats,
};
- return includeRealtime
+ return includeRealtime && wantsFullSummary
? realtimeStore.applySummaryDelta(resolvedBackendId, baseStats)
: baseStats;
}
diff --git a/apps/web/app/[locale]/page.tsx b/apps/web/app/[locale]/page.tsx
index 294952e..9ce5c67 100644
--- a/apps/web/app/[locale]/page.tsx
+++ b/apps/web/app/[locale]/page.tsx
@@ -112,6 +112,7 @@ const NAV_ITEMS = [
type TimePreset = "1m" | "5m" | "15m" | "30m" | "24h" | "7d" | "30d" | "today" | "custom";
type RollingTimePreset = Exclude<TimePreset, "custom">;
type BackendStatus = "healthy" | "unhealthy" | "unknown";
+const SUMMARY_WS_MIN_PUSH_MS = 3000;
function isRollingTimePreset(preset: TimePreset): preset is RollingTimePreset {
return preset !== "custom";
@@ -384,10 +385,7 @@ export default function DashboardPage() {
const stableTimeRange = useStableTimeRange(timeRange);
const isWsSummaryTab =
activeTab === "overview" ||
- activeTab === "domains" ||
- activeTab === "countries" ||
- activeTab === "proxies" ||
- activeTab === "devices";
+ activeTab === "countries";
const backendsQuery = useQuery({
queryKey: ["backends"],
@@ -412,6 +410,7 @@ export default function DashboardPage() {
const { status: wsStatus, lastMessage: wsSummary } = useStatsWebSocket({
backendId: activeBackendId,
range: stableTimeRange,
+ minPushIntervalMs: SUMMARY_WS_MIN_PUSH_MS,
enabled: wsEnabled,
onMessage: useCallback((stats: StatsSummary) => {
if (!activeBackendId) return;
diff --git a/apps/web/components/domains-table.tsx b/apps/web/components/domains-table.tsx
index 12d8422..135c878 100644
--- a/apps/web/components/domains-table.tsx
+++ b/apps/web/components/domains-table.tsx
@@ -40,6 +40,7 @@ type SortOrder = "asc" | "desc";
const PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
type PageSize = typeof PAGE_SIZE_OPTIONS[number];
const DETAIL_QUERY_STALE_MS = 30_000;
+const DOMAINS_WS_MIN_PUSH_MS = 3_000;
export function DomainsTable({ activeBackendId, timeRange, autoRefresh = true }: DomainsTableProps) {
const t = useTranslations("domains");
@@ -61,12 +62,14 @@ export function DomainsTable({ activeBackendId, timeRange, autoRefresh = true }:
const { status: wsPageStatus } = useStatsWebSocket({
backendId: activeBackendId,
range: stableTimeRange,
+ minPushIntervalMs: DOMAINS_WS_MIN_PUSH_MS,
includeDomainsPage: wsPageEnabled,
domainsPageOffset: pageOffset,
domainsPageLimit: pageSize,
domainsPageSortBy: sortKey,
domainsPageSortOrder: sortOrder,
domainsPageSearch: wsPageSearch,
+ trackLastMessage: false,
enabled: wsPageEnabled,
onMessage: useCallback((stats: StatsSummary) => {
const query = stats.domainsPageQuery;
diff --git a/apps/web/components/interactive-device-stats.tsx b/apps/web/components/interactive-device-stats.tsx
index 56f4d65..44acaec 100644
--- a/apps/web/components/interactive-device-stats.tsx
+++ b/apps/web/components/interactive-device-stats.tsx
@@ -30,6 +30,7 @@ interface InteractiveDeviceStatsProps {
backendStatus?: "healthy" | "unhealthy" | "unknown";
autoRefresh?: boolean;
}
+const DEVICE_DETAIL_WS_MIN_PUSH_MS = 3_000;
@@ -101,9 +102,11 @@ export function InteractiveDeviceStats({
const { status: wsDetailStatus } = useStatsWebSocket({
backendId: activeBackendId,
range: detailTimeRange,
+ minPushIntervalMs: DEVICE_DETAIL_WS_MIN_PUSH_MS,
includeDeviceDetails: wsDetailEnabled,
deviceSourceIP: selectedDevice ?? undefined,
deviceDetailLimit: 5000,
+ trackLastMessage: false,
enabled: wsDetailEnabled,
onMessage: useCallback((stats: StatsSummary) => {
if (!selectedDevice) return;
diff --git a/apps/web/components/interactive-proxy-stats.tsx b/apps/web/components/interactive-proxy-stats.tsx
index 44762e7..d947e0c 100644
--- a/apps/web/components/interactive-proxy-stats.tsx
+++ b/apps/web/components/interactive-proxy-stats.tsx
@@ -32,6 +32,7 @@ interface InteractiveProxyStatsProps {
backendStatus?: "healthy" | "unhealthy" | "unknown";
autoRefresh?: boolean;
}
+const PROXY_DETAIL_WS_MIN_PUSH_MS = 3_000;
function normalizeProxyName(name: string): string {
const normalized = name
@@ -137,9 +138,11 @@ export function InteractiveProxyStats({
const { status: wsDetailStatus } = useStatsWebSocket({
backendId: activeBackendId,
range: detailTimeRange,
+ minPushIntervalMs: PROXY_DETAIL_WS_MIN_PUSH_MS,
includeProxyDetails: wsDetailEnabled,
proxyChain: selectedProxy ?? undefined,
proxyDetailLimit: 5000,
+ trackLastMessage: false,
enabled: wsDetailEnabled,
onMessage: useCallback((stats: StatsSummary) => {
if (!selectedProxy) return;
diff --git a/apps/web/components/ips-table.tsx b/apps/web/components/ips-table.tsx
index cf97a70..6d6bcc1 100644
--- a/apps/web/components/ips-table.tsx
+++ b/apps/web/components/ips-table.tsx
@@ -59,6 +59,7 @@ type SortOrder = "asc" | "desc";
const PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
type PageSize = (typeof PAGE_SIZE_OPTIONS)[number];
const DETAIL_QUERY_STALE_MS = 30_000;
+const IPS_WS_MIN_PUSH_MS = 3_000;
// Color palette for IP icons - solid colors that work in both light/dark modes
const IP_COLORS = [
@@ -101,12 +102,14 @@ export function IPsTable({ activeBackendId, timeRange, autoRefresh = true }: IPs
const { status: wsPageStatus } = useStatsWebSocket({
backendId: activeBackendId,
range: stableTimeRange,
+ minPushIntervalMs: IPS_WS_MIN_PUSH_MS,
includeIPsPage: wsPageEnabled,
ipsPageOffset: pageOffset,
ipsPageLimit: pageSize,
ipsPageSortBy: sortKey,
ipsPageSortOrder: sortOrder,
ipsPageSearch: wsPageSearch,
+ trackLastMessage: false,
enabled: wsPageEnabled,
onMessage: useCallback((stats: StatsSummary) => {
const query = stats.ipsPageQuery;
diff --git a/apps/web/components/overview/index.tsx b/apps/web/components/overview/index.tsx
index 3bc5d74..098aca8 100644
--- a/apps/web/components/overview/index.tsx
+++ b/apps/web/components/overview/index.tsx
@@ -46,6 +46,7 @@ const ONE_HOUR_MS = 60 * 60 * 1000;
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
const REALTIME_END_TOLERANCE_MS = 2 * 60 * 1000;
const TREND_CACHE_TTL_MS = 60 * 1000;
+const TREND_WS_MIN_PUSH_MS = 3_000;
type TrendCacheEntry = {
data: TrafficTrendPoint[];
@@ -204,9 +205,11 @@ export function OverviewTab({
const { status: wsTrendStatus } = useStatsWebSocket({
backendId: activeBackendId,
range: { start: trendQuery.start, end: trendQuery.end },
+ minPushIntervalMs: TREND_WS_MIN_PUSH_MS,
includeTrend: wsTrendEnabled,
trendMinutes: trendQuery.minutes,
trendBucketMinutes: trendQuery.bucketMinutes,
+ trackLastMessage: false,
enabled: wsTrendEnabled,
onMessage: useCallback((stats: StatsSummary) => {
if (!stats.trendStats) return;