I am working on a nest js based project, where we are developing a notification service. This notifications service would be responsible for sending out notifications to our users.
The use case is that we have another microservice for assigning job shifts to our employees, we have configured a cron job that sends data to notification service when to send an email to a specific user.
I am using postgresql db. Now the problem that I am facing is of multiple timezones. The shift service sends me(notifications service) scheduledTime
by converting the time into UTC using the following method
private LocalDateTime toUTF(final LocalDateTime time, final ZoneId fromZone) {
return time.atZone(fromZone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}
Shift service then sends this UTC time and other data to notifications service which simply saves it inside the db. The table for holding the notification data in notifications service is this
CREATE TABLE "notifications" (
"id" SERIAL PRIMARY KEY,
"type" VARCHAR NOT NULL,
"status" VARCHAR NOT NULL,
"target" VARCHAR NOT NULL,
"message" VARCHAR NOT NULL,
"userId" INT,
"scheduledTime" TIMESTAMP WITHOUT TIMEZONE DEFAULT NULL,
"retries" integer NOT NULL DEFAULT 0,
"created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
"updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
deleted_at TIMESTAMP(6) NULL DEFAULT NULL
);
The problem is that the UTC time that is sent by the shift service is not exactly what I see in the db, it gets changed after its added into the db. Then I have put up a cron job in notifications service that runs every 30 minutes and tries to pick up notifications which are due to be sent in next 30 minutes. I have deployed my code on AWS EC2 instance with Aus/Sydney.
@Cron(CronExpression.EVERY_10_SECONDS)
async fetchUpComingNotificationFromDB() {
const currentTime = moment.utc().toDate();
this.logger.log(`Current Time in UTC: ${currentTime}`);
const targetTime = moment.utc().add(30, 'minutes').toDate();
this.logger.log({
message: 'Fetching upcoming notifications',
currentTime: currentTime.toLocaleString(),
targetTime: targetTime.toLocaleString(),
});
try {
const notifications: Notification[] = await this.notificationRepository
.createQueryBuilder('notification')
.where('notification.scheduledTime IS NOT NULL')
.andWhere(
'notification.scheduledTime BETWEEN :currentTime AND :targetTime',
{
currentTime,
targetTime,
},
)
.andWhere('notification.status = :status', { status: 'Pending' })
.getMany();
const jobs = await Promise.all(
notifications.map(async (notification) => {
const delay =
notification.scheduledTime.getTime() - new Date().getTime();
await this.notificationRepository.save({
...notification,
status: 'Queued',
type: normalizeString(notification.type),
});
return {
data: notification,
opts: {
delay,
removeOnFail: true,
removeOnComplete: true,
attempts: MAX_RETRIES,
backoff: {
type: 'exponential',
delay: 5000,
},
},
};
}),
);
if (jobs.length > 0) {
await this.notificationsQueue.addBulk(jobs);
this.logger.log({
message: `Added ${jobs.length} notifications to the queue`,
notifications: notifications.map((n) => ({
id: n.id,
target: n.target,
type: n.type,
})),
});
} else {
this.logger.log('No upcoming notifications to add to the queue');
}
} catch (error) {
this.logger.error({
message: 'Error fetching upcoming notifications',
error: error.toString(),
});
}
this.logger.log({
message: 'Finished fetching upcoming notifications',
time: moment().format('YYYY-MM-DD h:mm:ss A'),
});
}
but again my intended logic does not work as expected because of the mismatches in the UTC times and timezones. I am completely lost here. I would appreciate any help.
I tried converting the shift time into UTC and save it into Postgresql db, then I ran a cron job that will first make a currentTime
var with current UTC time in it and then will create a targetTime
var with 30 minutes addition from currentTime. Then I try to fetch the records from db that falls between currentTime and targetTime, then I calculate the delay and assign it to the queue. But because of the mismatch in UTC times the data never gets picked from db.