@@ -329,6 +329,8 @@ export class BunGateway implements Gateway {
329329 }
330330 }
331331
332+ // Measure end-to-end time to update latency metrics in the load balancer
333+ const startedAt = Date . now ( )
332334 increaseTargetConnectionsIfLeastConnections (
333335 route . loadBalancer ?. strategy ,
334336 target ,
@@ -347,12 +349,22 @@ export class BunGateway implements Gateway {
347349 route . loadBalancer ?. strategy ,
348350 target ,
349351 )
352+ // Update latency stats for strategies like 'latency' and as tie-breakers
353+ try {
354+ const duration = Date . now ( ) - startedAt
355+ loadBalancer . recordResponse ( target . url , duration , false )
356+ } catch { }
350357 } ,
351358 onError : ( req : Request , error : Error ) => {
352359 decreaseTargetConnectionsIfLeastConnections (
353360 route . loadBalancer ?. strategy ,
354361 target ,
355362 )
363+ // Record error with latency to penalize target appropriately
364+ try {
365+ const duration = Date . now ( ) - startedAt
366+ loadBalancer . recordResponse ( target . url , duration , true )
367+ } catch { }
356368 if ( route . hooks ?. onError ) {
357369 route . hooks . onError ! ( req , error )
358370 }
@@ -490,7 +502,13 @@ function increaseTargetConnectionsIfLeastConnections(
490502 strategy : string | undefined ,
491503 target : any ,
492504) : void {
493- if ( strategy === 'least-connections' && target . connections !== undefined ) {
505+ if (
506+ ( strategy === 'least-connections' ||
507+ strategy === 'weighted-least-connections' ||
508+ strategy === 'p2c' ||
509+ strategy === 'power-of-two-choices' ) &&
510+ target . connections !== undefined
511+ ) {
494512 target . connections ++
495513 }
496514}
@@ -499,7 +517,13 @@ function decreaseTargetConnectionsIfLeastConnections(
499517 strategy : string | undefined ,
500518 target : any ,
501519) : void {
502- if ( strategy === 'least-connections' && target . connections !== undefined ) {
520+ if (
521+ ( strategy === 'least-connections' ||
522+ strategy === 'weighted-least-connections' ||
523+ strategy === 'p2c' ||
524+ strategy === 'power-of-two-choices' ) &&
525+ target . connections !== undefined
526+ ) {
503527 target . connections --
504528 }
505529}
0 commit comments