Skip to content

Commit 2c6e3b8

Browse files
authored
Merge pull request #201 from vernu/2026-03-11-yigc
implement batch processing for FCM messages in heartbeat check task
2 parents a43cf11 + 60808db commit 2c6e3b8

File tree

1 file changed

+25
-14
lines changed

1 file changed

+25
-14
lines changed

api/src/gateway/tasks/heartbeat-check.task.ts

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import { Device, DeviceDocument } from '../schemas/device.schema'
66
import * as firebaseAdmin from 'firebase-admin'
77
import { Message } from 'firebase-admin/messaging'
88

9+
const FCM_BATCH_SIZE = 500
10+
911
@Injectable()
1012
export class HeartbeatCheckTask {
1113
private readonly logger = new Logger(HeartbeatCheckTask.name)
@@ -73,23 +75,32 @@ export class HeartbeatCheckTask {
7375
return
7476
}
7577

76-
// Send FCM messages
77-
const response = await firebaseAdmin.messaging().sendEach(fcmMessages)
78+
// Send FCM messages in batches (FCM allows max 500 per sendEach call)
79+
let totalSuccessCount = 0
80+
let totalFailureCount = 0
7881

79-
this.logger.log(
80-
`Sent ${response.successCount} heartbeat check FCM notification(s), ${response.failureCount} failed`,
81-
)
82+
for (let i = 0; i < fcmMessages.length; i += FCM_BATCH_SIZE) {
83+
const batch = fcmMessages.slice(i, i + FCM_BATCH_SIZE)
84+
const batchDeviceIds = deviceIds.slice(i, i + FCM_BATCH_SIZE)
85+
const response = await firebaseAdmin.messaging().sendEach(batch)
86+
87+
totalSuccessCount += response.successCount
88+
totalFailureCount += response.failureCount
8289

83-
// Log failures for debugging
84-
if (response.failureCount > 0) {
85-
response.responses.forEach((resp, index) => {
86-
if (!resp.success) {
87-
this.logger.error(
88-
`Failed to send heartbeat check to device ${deviceIds[index]}: ${resp.error?.message || 'Unknown error'}`,
89-
)
90-
}
91-
})
90+
if (response.failureCount > 0) {
91+
response.responses.forEach((resp, index) => {
92+
if (!resp.success) {
93+
this.logger.error(
94+
`Failed to send heartbeat check to device ${batchDeviceIds[index]}: ${resp.error?.message || 'Unknown error'}`,
95+
)
96+
}
97+
})
98+
}
9299
}
100+
101+
this.logger.log(
102+
`Sent ${totalSuccessCount} heartbeat check FCM notification(s), ${totalFailureCount} failed`,
103+
)
93104
} catch (error) {
94105
this.logger.error('Error checking and triggering stale heartbeats', error)
95106
}

0 commit comments

Comments
 (0)