// Cache for site data (5 minutes TTL)
const siteCache = new Map();
const SITE_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
const normDate = (d) => {
const x = new Date(d);
x.setHours(0, 0, 0, 0);
return x;
};
const dayIndex = (d) => new Date(d).getDay();
function* datesBetween(from, to) {
const s = normDate(from), e = normDate(to);
for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1))
yield new Date(d);
}
function genSpots(spotsPerHour, factor, offset, partialCount = null, fillOrder = "head") {
let arr = [];
if (factor === 0) {
for (let i = 1; i <= spotsPerHour; i++) arr.push(i);
} else {
const step = factor + 1;
const start = 1 + (offset || 0);
for (let i = start; i <= spotsPerHour; i += step) arr.push(i);
}
if (Number.isInteger(partialCount) && partialCount >= 0) {
arr = fillOrder === "tail" ? arr.slice(-partialCount) : arr.slice(0, partialCount);
}
return arr;
}
if (!fromDate || !toDate) throw new Error("fromDate and toDate are required");
if (!["spot", "slot"].includes(bookingType))
throw new Error('bookingType must be "spot" or "slot"');
if (![0, 1, 2].includes(factor)) throw new Error("factor must be 0|1|2");
if (!Array.isArray(siteIds) || siteIds.length === 0)
throw new Error("siteIds must be a non-empty array");
if (!Array.isArray(daily) || daily.length === 0)
throw new Error("daily patterns are required");
if ((bookingType === "slot" || bookingType === "spot") &&
!(Number.isInteger(numberOfSlots) && numberOfSlots > 0)) {
throw new Error("numberOfSlots must be a positive integer for slot and spot bookings");
}
if (!(offset === "auto" || (Number.isInteger(offset) && offset >= 0 && offset <= factor))) {
throw new Error('offset must be "auto" or an integer 0..factor');
}
if (!["head", "tail"].includes(fillOrder))
throw new Error('fillOrder must be "head" or "tail"');
for (const p of daily) {
if (!Array.isArray(p.days) || p.days.length === 0)
throw new Error("each daily pattern needs days[]");
if (![p.startHour, p.endHour].every(h => Number.isInteger(h) && h >= 0 && h <= 23)) {
throw new Error("startHour/endHour must be 0..23");
}
if (![p.startMinutes, p.endMinutes].every(m => Number.isInteger(m) && m >= 0 && m < 60)) {
throw new Error("startMinutes/endMinutes must be 0..59");
}
if (!Number.isInteger(p.duration) || p.duration <= 0)
throw new Error("duration (minutes) required");
}
// Create nested lookup map for conflicts
const conflictMap = new Map();
conflicts.forEach(conflict => {
const siteKey = ${conflict.siteId}-${conflict.bookingDate.toISOString()};
if (!conflictMap.has(siteKey)) {
conflictMap.set(siteKey, new Map());
}
code
const slotHourKey = `${conflict.slotNumber}-${conflict.hour}`;
if (!conflictMap.get(siteKey).has(slotHourKey)) {
conflictMap.get(siteKey).set(slotHourKey, new Set());
}
conflictMap.get(siteKey).get(slotHourKey).add(conflict.spotNumber);
});
return conflictMap;
}
// OPTIMIZED: Process all slots for a site-date combination
function findFreeSlots(takenSlots, totalSlots, numberOfSlots) {
const available = [];
for (let slot = 1; slot <= totalSlots; slot++) {
if (!takenSlots || !takenSlots.has(slot)) {
available.push(slot);
if (available.length === numberOfSlots) break;
}
}
return available;
}
// OPTIMIZED: Main plan building function
async function buildPlanOptimized(body) {
const settings = validatePayload(body);
const { bookingType, factor, offset, siteIds, numberOfSlots, allOrNothing, fillOrder } = settings;
// Get sites with caching
const sites = await getSitesOptimized(siteIds);
if (sites.length !== siteIds.length) throw new Error("Some siteIds not found");
for (const date of dates) {
if (isSlotBooking) {
// For slot bookings, book all spots for all hours
const spotsPerHour = spotsData.spotsPerHour || 30;
for (let hour = 0; hour < 24; hour++) {
for (let spotNumber = 1; spotNumber <= spotsPerHour; spotNumber++) {
allDocs.push({
bookingId,
siteId,
bookingDate: date,
slotNumber,
hour,
spotNumber,
});
}
}
} else {
// For spot bookings, book specific spots for specific hours
for (const spotDetail of spotsData) {
if (spotDetail.slotNumber === slotNumber) {
for (const spot of spotDetail.spots) {
allDocs.push({
bookingId,
siteId,
bookingDate: date,
slotNumber: spotDetail.slotNumber,
hour: spotDetail.hour,
spotNumber: spot,
});
}
}
}
}
}
// Batch insert all documents at once
if (allDocs.length > 0) {
const batchSize = 1000; // Insert in batches to avoid memory issues
for (let i = 0; i < allDocs.length; i += batchSize) {
const batch = allDocs.slice(i, i + batchSize);
await BookingSpot.insertMany(batch, { ordered: false });
}
}
}
// OPTIMIZED: Create booking records in batches
async function createBookingRecordsOptimized(bookingMetadataId, settings, sites, planBySite) {
const { fromDate, toDate, bookingType, factor, daily, status, jnumbers, agentId, createdBy, client } = settings;
for (const sitePlan of planBySite) {
const site = sites.find(s => s._id.toString() === sitePlan.siteId.toString());
if (!site) continue;
code
for (let pIdx = 0; pIdx < daily.length; pIdx++) {
const sample = daily[pIdx];
const relatedBookings = sitePlan.bookings.filter(b => b.patternIdx === pIdx);
if (relatedBookings.length === 0) continue;
// Collect all unique slots for this pattern
const allSlots = new Set();
relatedBookings.forEach(booking => {
if (bookingType === "slot") {
(booking.slotsBooked || []).forEach(slot => allSlots.add(slot));
} else {
(booking.spotPlans || []).forEach(plan => allSlots.add(plan.slotNumber));
}
});
// Create booking records for each slot
for (const slotNumber of allSlots) {
const bookingDoc = {
bookingMetadataId,
fromDate, toDate, bookingType, factor,
days: sample.days,
startHour: sample.startHour,
startMinutes: sample.startMinutes,
endHour: sample.endHour,
endMinutes: sample.endMinutes,
startTime: sample.startTime,
endTime: sample.endTime,
duration: sample.duration,
numberOfSlots: 1,
status,
jnumber: jnumbers[0] || "",
siteId: String(sitePlan.siteId),
agentId, createdBy, client,
slotNumber,
};
bookingDocs.push(bookingDoc);
}
}
}
// Batch insert all booking records
const createdBookings = await Booking.insertMany(bookingDocs);
// Create booking spots in parallel
let bookingIndex = 0;
for (const sitePlan of planBySite) {
const site = sites.find(s => s._id.toString() === sitePlan.siteId.toString());
if (!site) continue;
// First check availability (optimized)
const plan = await buildPlanOptimized(req.body);
if (!plan.success) {
console.timeEnd('createBooking');
return res.status(409).json({
success: false,
error: "All-or-nothing violated",
details: plan,
});
}
const settings = validatePayload(req.body);
console.log("Creating booking with optimized process");
// Create metadata record
console.time('createMetadata');
const meta = await BookingMetadata.create({
fromDate: settings.fromDate,
toDate: settings.toDate,
bookingType: settings.bookingType,
factor: settings.factor,
daily: settings.daily,
numberOfSlots: settings.numberOfSlots,
status: settings.status,
jnumbers: settings.jnumbers,
siteIds: settings.siteIds,
comments: settings.comments,
agentId: settings.agentId,
createdBy: settings.createdBy,
client: settings.client,
});
console.timeEnd('createMetadata');
// Get sites (cached)
const sites = await getSitesOptimized(settings.siteIds);
// Create all booking records and spots in batches
console.time('createBookingRecords');
await createBookingRecordsOptimized(meta._id, settings, sites, plan.planBySite);
console.timeEnd('createBookingRecords');
console.timeEnd('createBooking');
return res.json({ success: true, plan });
} catch (err) {
console.error('createBooking error:', err);
return res.status(400).json({ success: false, error: err.message });
}
},
};
when i have 2 -3 month booking it's create 1M+ records in bookingspot table and Api is also taking 7 to 10 min
can we change database schema and still archive same thing but very optimize way
You're absolutely right to be concerned about the massive number of records and the resulting API latency. Creating 1M+ records in a single transaction is a recipe for performance issues. Here's a breakdown of potential database schema changes and optimization strategies to address this, while still achieving the same functionality.
Understanding the Bottleneck
The primary bottleneck is the sheer volume of data being inserted into the BookingSpot table. This leads to:
Increased Write Operations: Each record insertion is a disk I/O operation, which is relatively slow.
Database Locking: High write volume can lead to increased locking contention, slowing down operations.
Memory Pressure: Inserting a large number of records can put significant pressure on the database server's memory.
API Timeouts: The API request might time out due to the prolonged insertion process.
Database Schema Changes for Optimization
Here are a few schema modifications to consider:
1. Separate Booking and Spot Details (Recommended)
This is the most significant change and offers the most flexibility and potential for optimization.
BookingMetadata (No Changes Needed): Remains the central record for booking information.
Reduced Record Count: Instead of one record per slot/spot combination, you have separate records for each.
Faster Queries: Queries for specific spot availability or booking details become more efficient.
Easier Aggregations: Analyzing spot usage and availability is simpler.
2. Batching within the BookingSpot Table (Less Ideal for Massive Data)
You could still have a single BookingSpot table but insert data in larger batches. This can help reduce the number of individual write operations.
Implement a batching mechanism in your backend code.
Insert records in chunks (e.g., 1000-10000 records per batch).
Limitations:
Still a large number of records: Even with batching, 1M+ records can be a lot.
Potential for transaction timeouts: Very large batches might still lead to transaction timeouts.
Optimization Strategies
Regardless of the schema change, these strategies are crucial:
1. Asynchronous Operations and Queues:
Offload booking spot creation to a background job queue (e.g., RabbitMQ, Kafka).
The API can quickly insert the Booking record and then enqueue the spot creation tasks.
Worker processes can then process these tasks in batches, reducing the load on the main API thread.
2. Bulk Inserts:
Utilize Mongoose's insertMany() method for bulk insertions. This is significantly more efficient than inserting records one by one.
3. Connection Pooling:
Ensure your database connection pool is configured correctly to handle a high volume of concurrent requests.
4. Database Indexing:
Ensure appropriate indexes are in place on the BookingSpot table:
bookingId
siteId
bookingDate
slotNumber
hour
spotNumber
Consider compound indexes for frequently used query patterns.
5. Optimize Data Retrieval:
If you frequently query BookingSpot data, optimize your queries with appropriate indexes.
Consider using pagination to limit the amount of data returned in a single request.
6. Consider a Different Database (If Necessary):
For extremely high write volumes, consider NoSQL databases like MongoDB. MongoDB's schema flexibility and ability to handle large volumes of data can be advantageous. However, this would involve a significant architectural change.
Implementation Steps
Prioritize Schema Change: The separate Booking and BookingSpot schema is the most recommended approach for long-term scalability and maintainability.
Implement Background Job Queue: This is crucial for handling the large number of spot creations asynchronously.
Utilize Bulk Inserts: Use insertMany() in your backend code.
Optimize Indexes: Ensure proper indexing on the BookingSpot table.
Monitor Performance: Continuously monitor your database performance and adjust your strategies as needed.
Estimated Time Reduction
By implementing these changes, you should see a significant reduction in API response times. Offloading the spot creation to a queue and using bulk inserts can potentially reduce the insertion time from 7-10 minutes to a few seconds or minutes, depending on the number of records and the efficiency of your backend implementation.
Important Considerations:
Data Consistency: Ensure that your background job processing maintains data consistency between the Booking and BookingSpot records.
Error Handling: Implement robust error handling for background job processing.
Transaction Management: Carefully consider transaction boundaries when using background jobs.
By combining these schema changes and optimization strategies, you can significantly improve the performance and scalability of your booking system. Remember to test thoroughly after implementing any changes.