Migrate Ashby file processing from Next.js API routes to Supabase Edge Functions to solve performance and reliability issues during bulk candidate syncing operations.
- Server Overload: When syncing 100+ candidates, simultaneous HTTP requests to
/api/ashby/filesoverwhelm the Next.js server, causing 500 errors - Resource Waste: File downloads consume Next.js server resources that should be reserved for user-facing operations
- Poor Scalability: No built-in concurrency control or queuing mechanism
- Complex Error Handling: Network timeouts and HTTP failures are difficult to handle gracefully
- Rate Limiting: Parallel requests to Ashby API increase chances of hitting rate limits
Database Trigger → HTTP POST to Next.js → Ashby API → Supabase Storage → Database Updates
Database Trigger → Supabase Edge Function → Ashby API → Supabase Storage → Database Updates
- Built-in Queuing: Supabase manages function invocation queue automatically
- Resource Isolation: File processing doesn't impact main application server
- Better Error Handling: Built-in retries and failure management
- Natural Rate Limiting: Queue prevents overwhelming external APIs
- Simplified Architecture: Removes unnecessary HTTP round-trip
- File Download: Fetch resume files from Ashby using file handles
- Storage Upload: Store files in Supabase Storage (
candidate-cvsbucket) - Database Updates: Update
files,ashby_candidates, andapplicantstables - Status Tracking: Update processing status throughout the workflow
- Error Handling: Graceful failure handling with appropriate logging
- Handle up to 1000 file processing requests per bulk sync
- Process files within 30 seconds per file
- Maintain 99% success rate for file downloads
- Zero impact on Next.js application performance
- Authenticate using service role key for database access
- Validate input parameters (candidateId, fileHandle, userId)
- Ensure proper file type validation (PDF, DOC, DOCX)
- Maintain user data isolation through RLS policies
Add file_processing_status column to ashby_candidates table to track progress:
Status Values:
pending- File processing not yet startedprocessing- Edge function currently processing filecompleted- File successfully processed and storedfailed- Processing failed with error
Implementation:
ALTER TABLE ashby_candidates ADD COLUMN file_processing_status TEXT DEFAULT 'pending';
CREATE INDEX idx_ashby_candidates_processing_status ON ashby_candidates(file_processing_status);Progress Monitoring:
- Frontend can query:
SELECT COUNT(*) FROM ashby_candidates WHERE file_processing_status = 'completed' - Real-time progress:
SELECT file_processing_status, COUNT(*) FROM ashby_candidates GROUP BY file_processing_status - Error tracking:
SELECT * FROM ashby_candidates WHERE file_processing_status = 'failed'
Edge Function Workflow:
- Set status to
processingwhen function starts - Update to
completedon successful file storage - Update to
failedwith error logging on any failure - Include status updates in all database transactions
- Add
file_processing_statuscolumn toashby_candidatestable - Create index for efficient status queries
- Update existing records to
pendingstatus
- Create
supabase/functions/process-ashby-file/index.ts - Implement file download and storage logic with status updates
- Add comprehensive error handling and logging
- Test with individual file processing and status tracking
- Update trigger function to call edge function instead of HTTP endpoint
- Remove bulk sync session complexity (no longer needed)
- Test trigger with small batches and verify status updates
- Remove
/api/ashby/filesNext.js API route - Clean up unused bulk sync database functions
- Update documentation and remove obsolete code
- Test with progressively larger candidate batches
- Monitor edge function performance and error rates
- Verify status tracking accuracy during bulk operations
- Deploy to production with comprehensive monitoring
From /api/ashby/files/route.ts:
- File handle parsing logic (lines 28-48)
- Ashby API client integration (lines 110-127)
- File download logic (lines 129-148)
- Storage upload logic (lines 154-169)
- Database record creation (lines 172-184)
- Candidate/applicant updates (lines 194-229)
- Next.js API Route: Entire
/api/ashby/files/route.tsfile - Bulk Sync Functions: Database functions in migration
20250827000000_optimize_bulk_file_processing.sql:bulk_sync_sessionstableis_bulk_sync_active()functionstart_bulk_sync_session()functionend_bulk_sync_session()functionprocess_deferred_files()function
- Complex Trigger Logic: Simplified trigger function (no bulk detection needed)
- API Route References: Remove bulk session calls from
/api/ashby/candidates/route.ts
- Ashby client library (
/lib/ashby/client.ts) - File storage utilities (
/lib/fileStorage.ts) - Database types and interfaces
- Error handling patterns
- Bulk Sync Success Rate: >99% for 1000+ candidate operations
- File Processing Latency: <30 seconds per file
- Server Resource Usage: 0% impact on Next.js server during bulk operations
- API Rate Limit Hits: <1% of requests to Ashby API
- Error Rate: <1% for file processing operations
- Data Consistency: 100% accuracy in file-to-candidate linking
- Storage Success Rate: >99.9% for file uploads to Supabase Storage
- Status Accuracy: 100% of files have correct processing status
- Progress Visibility: Real-time status updates during bulk operations
- Error Transparency: Failed processing clearly identified with error details
- Completion Detection: Accurate count of total vs processed files
- Edge Function Cold Starts: May cause initial delays (Mitigation: Keep functions warm)
- Supabase Service Limits: Function timeout limits (Mitigation: Optimize processing time)
- Database Connection Limits: Too many concurrent connections (Mitigation: Connection pooling)
- Implement comprehensive logging for debugging
- Add retry logic for transient failures
- Monitor function performance metrics
- Maintain fallback to manual file processing
- Week 1: Edge function development and testing
- Week 2: Database migration and trigger updates
- Week 3: Cleanup and integration testing
- Week 4: Production deployment and monitoring
- Supabase Edge Functions enabled on project
- Ashby API access and file handle permissions
- Supabase Storage bucket configuration
- Database migration capabilities
- ✅ Edge function successfully processes individual files
- ✅ Bulk sync of 1000+ candidates completes without 500 errors
- ✅ All files are correctly stored and linked to candidates
- ✅ Next.js server performance unaffected during bulk operations
- ✅ No data loss or corruption during migration
- ✅ Comprehensive error logging and monitoring in place
- ✅ File processing status accurately tracked throughout workflow
- ✅ Progress visibility available for bulk operations (completed/total counts)
- ✅ Failed file processing clearly identified with error details
- ✅ Status queries perform efficiently with proper database indexing