@@ -30,8 +30,8 @@ interface SecurityEvent {
3030class OptimizedAnalyticsCollector {
3131 private requestBatch : RequestAnalytics [ ] = [ ] ;
3232 private securityBatch : SecurityEvent [ ] = [ ] ;
33- private readonly BATCH_SIZE = 50 ; // Batch writes for performance
34- private readonly FLUSH_INTERVAL = 30000 ; // 30 seconds
33+ private readonly BATCH_SIZE = 100 ; // Larger batches for better efficiency
34+ private readonly FLUSH_INTERVAL = 15000 ; // 15 seconds - faster flushing
3535 private flushTimer : NodeJS . Timeout | null = null ;
3636
3737 constructor ( ) {
@@ -69,36 +69,41 @@ class OptimizedAnalyticsCollector {
6969 }
7070 }
7171
72- // Optimized database write with batching
72+ // Optimized database write with batching and connection management
7373 private async flushRequests ( ) {
7474 if ( this . requestBatch . length === 0 ) return ;
7575
7676 const batch = [ ...this . requestBatch ] ;
7777 this . requestBatch = [ ] ;
7878
7979 try {
80- await prisma . analyticsRequest . createMany ( {
81- data : batch . map ( req => ( {
82- timestamp : req . timestamp ,
83- endpoint : req . endpoint ,
84- method : req . method ,
85- statusCode : req . statusCode ,
86- responseTime : req . responseTime ,
87- clientId : req . clientId ,
88- userId : req . userId ,
89- ipAddress : req . ipAddress ,
90- userAgent : req . userAgent ,
91- country : req . country ,
92- city : req . city ,
93- clientType : req . clientType ,
94- platform : req . platform
95- } ) ) ,
96- skipDuplicates : true // Prevent errors on duplicate inserts
80+ // Use transaction for better connection management
81+ await prisma . $transaction ( async ( tx ) => {
82+ await tx . analyticsRequest . createMany ( {
83+ data : batch . map ( req => ( {
84+ timestamp : req . timestamp ,
85+ endpoint : req . endpoint ,
86+ method : req . method ,
87+ statusCode : req . statusCode ,
88+ responseTime : req . responseTime ,
89+ clientId : req . clientId ,
90+ userId : req . userId ,
91+ ipAddress : req . ipAddress ,
92+ userAgent : req . userAgent ,
93+ country : req . country ,
94+ city : req . city ,
95+ clientType : req . clientType ,
96+ platform : req . platform
97+ } ) ) ,
98+ skipDuplicates : true
99+ } ) ;
97100 } ) ;
98101 } catch ( error ) {
99102 console . error ( 'Failed to flush analytics requests:' , error ) ;
100- // Re-add failed batch to retry later
101- this . requestBatch . unshift ( ...batch ) ;
103+ // Re-add failed batch to retry later (with limit to prevent infinite growth)
104+ if ( this . requestBatch . length < this . BATCH_SIZE * 2 ) {
105+ this . requestBatch . unshift ( ...batch ) ;
106+ }
102107 }
103108 }
104109
0 commit comments