You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently, when users exceed their database or storage limits, they only receive HTTP 403 errors when attempting operations. There's no proactive notification system to warn users before they hit these limits, which can lead to:
Unexpected service disruptions
Poor user experience
Users not realizing they're approaching limits
Additional Challenge: For users with BYOD (Bring Your Own Database), the current system doesn't track usage at all, making limit warnings impossible.
This feature will implement an email notification system that:
Alerts users when approaching resource limits
Supports custom thresholds for BYOD users (user-defined limits)
Calculates external database usage using MongoDB stats
Allows users to configure alert preferences
🎯 Problem Statement
Current Behavior:
Users only know about limit issues when operations fail (403 errors)
No proactive warnings before hitting limits
Email infrastructure exists but isn't used for limit notifications
Example scenario:
User has 500MB storage limit
They upload files and reach 490MB (98% usage)
Next upload fails with 403 error ❌
User is surprised and frustrated
Desired Behavior:
User reaches 400MB (80% of 500MB limit)
System sends email: "You're using 80% of your storage limit" ✅
User gets advance warning and can take action
BYOD User Scenario:
User connects their own MongoDB Atlas database
User sets custom threshold: "Alert me at 2GB usage"
System periodically calculates external DB size using MongoDB stats
When 2GB is reached, email sent ✅
💡 Proposed Solution
Implement a threshold-based email notification system that:
Monitors resource usage when users perform operations
Calculates external DB usage for BYOD users using MongoDB db.stats()
Supports configurable thresholds:
Managed DB: Percentage-based (80%, 95% of plan limit)
BYOD: Absolute value (user sets: "Alert at 2GB")
Triggers email alerts at configured thresholds
Prevents spam by sending max 1 email per threshold per 7 days
User preferences UI to configure alert thresholds
✅ Acceptance Criteria
Backend Requirements
Storage Limit Monitoring
Modify backend/controllers/storage.controller.js to check usage percentage
Trigger email when usage crosses 80% threshold
Track when last notification was sent (avoid spamming)
Database Limit Monitoring
Modify backend/controllers/data.controller.js to check database size
For BYOD databases: Calculate usage using db.stats() via external connection
For managed databases: Use existing tracking + percentage thresholds
constconnectionManager=require('./connection.manager');constCACHE_DURATION=60*60*1000;// 1 hour in msconstcalculateExternalDbSize=async(project)=>{// Check cache firstconstcached=project.cachedUsageStats?.database;if(cached&&(Date.now()-newDate(cached.lastCalculated))<CACHE_DURATION){returncached.size;}// If external database (BYOD)if(project.databaseConfig?.isExternal){try{constconnection=awaitconnectionManager.getConnection(project._id);conststats=awaitconnection.db.stats();constsizeInMB=Math.round(stats.dataSize/(1024*1024));// Update cacheawaitproject.updateOne({'cachedUsageStats.database': {size: sizeInMB,lastCalculated: newDate()}});returnsizeInMB;}catch(error){console.error('Failed to calculate external DB size:',error);returncached?.size||0;// Return cached value on error}}// For internal/managed databases, use existing trackingreturnproject.databaseSizeMB||0;};module.exports={ calculateExternalDbSize };
2️⃣ Create Email Template
File:backend/utils/emailTemplates/limitWarning.js
constlimitWarningTemplate=({ userName, projectName, resourceType, currentUsage, limit, percentage, isBYOD })=>{constalertTypeText=isBYOD
? `Your custom alert threshold of <strong>${limit}</strong> has been reached.`
: `You're currently using <strong>${percentage}%</strong> of your ${resourceType} limit.`;return` <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; } .container { max-width: 600px; margin: 0 auto; padding: 20px; } .warning-box { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; } .stats { background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0; } .action-button { background: #007bff; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block; margin-top: 15px; } </style> </head> <body> <div class="container"> <h2>⚠️ Resource Limit Alert</h2> <p>Hi ${userName},</p> <div class="warning-box"> <strong>Project:</strong> ${projectName}<br>${alertTypeText} </div> <div class="stats"> <strong>Current ${resourceType} usage:</strong> ${currentUsage}<br>${!isBYOD ? `<strong>Plan limit:</strong> ${limit}<br>` : ''}${!isBYOD ? `<strong>Usage:</strong> ${percentage}%` : ''} </div> <p><strong>What you can do:</strong></p> <ul> <li>Delete unused ${resourceType==='storage' ? 'files' : 'data'}</li>${!isBYOD ? '<li>Upgrade your plan for higher limits</li>' : '<li>Increase your database capacity</li>'} <li>Review and optimize your ${resourceType} usage</li>${isBYOD ? '<li>Adjust alert thresholds in project settings</li>' : ''} </ul> <a href="https://urbackend.com/dashboard" class="action-button">Go to Dashboard</a> <p style="color: #666; font-size: 12px; margin-top: 30px;">${isBYOD ? 'This is a custom alert you configured.' : 'You will receive this alert once per threshold.'} You can manage alert preferences in your project settings. </p> <p>Best regards,<br>urBackend Team</p> </div> </body> </html> `;};module.exports=limitWarningTemplate;
constemailQueue=require('../queues/emailQueue');constlimitWarningTemplate=require('./emailTemplates/limitWarning');const{ calculateExternalDbSize }=require('./calculateExternalDbSize');constCOOLDOWN_DAYS=7;constshouldSendNotification=(lastSent)=>{if(!lastSent)returntrue;constdaysSince=(Date.now()-newDate(lastSent))/(1000*60*60*24);returndaysSince>=COOLDOWN_DAYS;};constcheckAndNotify=async({ project, resourceType, currentUsageMB, owner })=>{// Check if notifications are enabledconstsettings=project.notificationSettings?.email;if(!settings?.enabled)return;constresourceSettings=settings[resourceType];constisBYOD=project.databaseConfig?.isExternal||project.storageConfig?.isExternal;letshouldAlert=false;letthreshold=null;letpercentage=null;// For BYOD with absolute limitsif(resourceSettings.type==='absolute'&&resourceSettings.absoluteLimit){if(currentUsageMB>=resourceSettings.absoluteLimit){shouldAlert=true;threshold='custom';}}// For managed resources with percentage thresholdselseif(resourceSettings.type==='percentage'){constlimit=resourceType==='storage'
? project.storageLimitMB
: project.databaseLimitMB;percentage=(currentUsageMB/limit)*100;// Find highest crossed thresholdconstthresholds=resourceSettings.thresholds||[80,95];for(constthreshofthresholds.sort((a,b)=>b-a)){if(percentage>=thresh){shouldAlert=true;threshold=`threshold${thresh}`;break;}}}if(!shouldAlert)return;// Check cooldown periodconstlastSent=project.lastLimitNotification?.[resourceType]?.[threshold];if(!shouldSendNotification(lastSent))return;// Send emailawaitemailQueue.add('limit-warning',{email: owner.email,userName: owner.name,projectName: project.name,
resourceType,currentUsage: `${currentUsageMB}MB`,limit: resourceSettings.type==='absolute'
? `${resourceSettings.absoluteLimit}MB`
: `${resourceType==='storage' ? project.storageLimitMB : project.databaseLimitMB}MB`,percentage: percentage ? Math.round(percentage) : null,
isBYOD
});// Update last notification timestampconstupdatePath=`lastLimitNotification.${resourceType}.${threshold}`;awaitproject.updateOne({[updatePath]: newDate()});console.log(`✅ Limit alert sent for ${resourceType} on project ${project.name}`);};module.exports={ checkAndNotify };
5️⃣ Modify Storage Controller
File:backend/controllers/storage.controller.js
Add notification check in upload function (around line 21):
const{ checkAndNotify }=require('../utils/limitNotificationHelper');constUser=require('../models/User');// After calculating current storage usageconstcurrentUsageMB=project.storageUsed||0;constowner=awaitUser.findById(project.owner);// Check and send notification if neededawaitcheckAndNotify({
project,resourceType: 'storage',
currentUsageMB,
owner
});
6️⃣ Modify Data Controller
File:backend/controllers/data.controller.js
Add notification check in POST/PUT operations (around line 34):
const{ checkAndNotify }=require('../utils/limitNotificationHelper');const{ calculateExternalDbSize }=require('../utils/calculateExternalDbSize');constUser=require('../models/User');// Calculate database size (works for both managed and BYOD)constcurrentUsageMB=awaitcalculateExternalDbSize(project);constowner=awaitUser.findById(project.owner);awaitcheckAndNotify({
project,resourceType: 'database',
currentUsageMB,
owner
});
📋 Description
Currently, when users exceed their database or storage limits, they only receive HTTP 403 errors when attempting operations. There's no proactive notification system to warn users before they hit these limits, which can lead to:
Additional Challenge: For users with BYOD (Bring Your Own Database), the current system doesn't track usage at all, making limit warnings impossible.
This feature will implement an email notification system that:
🎯 Problem Statement
Current Behavior:
Example scenario:
Desired Behavior:
BYOD User Scenario:
💡 Proposed Solution
Implement a threshold-based email notification system that:
db.stats()✅ Acceptance Criteria
Backend Requirements
Storage Limit Monitoring
backend/controllers/storage.controller.jsto check usage percentageDatabase Limit Monitoring
backend/controllers/data.controller.jsto check database sizedb.stats()via external connectionExternal Database Usage Calculation
backend/utils/calculateExternalDbSize.jsdb.stats()to get database sizeEmail Template
backend/utils/emailTemplates/limitWarning.jsNotification Tracking & Preferences
notificationSettingsandlastLimitNotificationEmail Queue Integration
backend/queues/emailQueue.js)limit-warningFrontend Requirements
User Settings UI - Project Settings Page
Visual Warnings (Optional Enhancement)
Testing
Unit Tests
Integration Tests
🛠️ Technical Implementation Guide
Files to Modify/Create
1️⃣ Create External DB Usage Calculator
File:
backend/utils/calculateExternalDbSize.js(NEW)2️⃣ Create Email Template
File:
backend/utils/emailTemplates/limitWarning.js3️⃣ Update Project Model
File:
backend/models/Project.jsAdd notification settings and tracking:
4️⃣ Create Notification Helper
File:
backend/utils/limitNotificationHelper.js(NEW)5️⃣ Modify Storage Controller
File:
backend/controllers/storage.controller.jsAdd notification check in upload function (around line 21):
6️⃣ Modify Data Controller
File:
backend/controllers/data.controller.jsAdd notification check in POST/PUT operations (around line 34):
7️⃣ Update Email Queue
File:
backend/queues/emailQueue.jsAdd new job processor for
limit-warning:8️⃣ Frontend: Project Settings UI
File:
frontend/src/pages/ProjectSettings.jsx(or create new component)Add alert configuration UI:
9️⃣ Frontend: API Endpoint for Settings
File:
backend/routes/project.routes.jsAdd endpoint to update notification settings:
📊 Testing Checklist
Manual Testing
Managed Database/Storage:
BYOD (External Database):
db.stats()is called to calculate usageAutomated Tests
🏷️ Labels
enhancementgood first issue❌ (This is intermediate)intermediate✅backendfrontendemailhelp wanted📚 Resources
Existing Code to Reference:
backend/utils/emailService.jsbackend/queues/emailQueue.jsbackend/controllers/storage.controller.js(line 21)backend/controllers/data.controller.js(line 34)backend/utils/connection.manager.js⭐ (critical for external DB access)backend/utils/encryption.js(how BYOD credentials are stored)db.stats()docs: https://www.mongodb.com/docs/manual/reference/method/db.stats/Similar Patterns in Codebase:
backend/utils/emailTemplates/(if exists)backend/queues/injectModel.jsuses connection manager🎓 Learning Outcomes
By completing this issue, you will learn:
db.stats())💬 Questions?
Feel free to ask questions in the comments if you need:
🚀 Estimated Time
Time to complete: 5-7 hours (for intermediate developer)
Breakdown:
👥 Assignee
Looking for an intermediate-advanced contributor who has:
db.stats()and connection management)Difficulty Level: ⭐⭐⭐ Intermediate-Advanced (upgraded from basic intermediate due to BYOD complexity)
Ready to tackle this? Drop a comment and get started! 🎯