卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章79808本站已运行4416

Cron 作业中聚合的力量和成本效益

cron 作业中聚合的力量和成本效益

在开发我的 saas 产品时,我发现,对于 10k 用户,您每天需要 10,001 次查询,并定期进行数据库查询来重置积分或免费提示。通过智能聚合,无论您有 10k 还是 100k 用户,您都只需要 2 次查询!

首先,让我给您一些 mongodb 生产数据库的成本审查(10k 和 1 年):

正常方式,每日查询:10,001
年度查询:10,001 x 365 = 3,650,365 次查询
年度费用:3,650,365 x 0.001 美元 = 3,650.37 美元

聚合方式,每日查询:2
年度查询:2 x 365 = 730 次查询
年度费用:730 x 0.001 美元 = 0.73 美元

节省:3,650.37 - 0.73 = 3,649.64 美元(近 40 万泰铢)

太棒了,现在看看传统的查询方法(为每个用户进行一个查询)

const resetlimitsforusers = async () => {
  const users = await user.find({ /* conditions to select users */ });

  for (const user of users) {
    if (user.plan.remaining_prompt_count 



<p>这里,如果您有 10,000 个用户,这会导致 10,001 个查询(每个用户 1 个,加上用于获取用户的初始查询) - 这是巨大的..</p>

<p>现在是英雄条目,[看起来有点困难,但它可以节省大量的钱]<br></p>

<pre class="brush:php;toolbar:false">const resetPlanCounts = () =&gt; {
  cron.schedule('* * * * *', async () =&gt; {
    try {
      const twoMinutesAgo = new Date(Date.now() - 2 * 60 * 1000); // 2 minutes ago

      const usersWithRegisteredPlan = await User.aggregate([
        {
          $match: {
            createdAt: { $lte: twoMinutesAgo },
            plan: { $exists: true }
          }
        },
        {
          $lookup: {
            from: 'plans',
            localField: 'plan',
            foreignField: '_id',
            as: 'planDetails'
          }
        },
        {
          $unwind: '$planDetails'
        },
        {
          $match: {
            'planDetails.name': 'Registered',
            $or: [
              { 'planDetails.remaining_prompt_count': { $lt: 3 } },
              { 'planDetails.remaining_page_count': { $lt: 3 } }
            ]
          }
        },
        {
          $project: {
            planId: '$planDetails._id'
          }
        }
      ]);

      const planIds = usersWithRegisteredPlan.map(user =&gt; user.planId);

      if (planIds.length &gt; 0) {
        const { modifiedCount } = await Plan.updateMany(
          { _id: { $in: planIds } },
          { $set: { remaining_prompt_count: 3, total_prompt_count: 3, remaining_page_count: 3, total_page_count: 3 } }
        );

        console.log(`${modifiedCount} plans reset for "Registered" users.`);
      } else {
        console.log('No plans to reset for today.');
      }
    } catch (error) {
      console.error('Error resetting plan counts:', error);
    }
  });
};

这就是您如何运行 cron 作业 [它在特定时间自动运行] 来更新所有 10k 用户积分或限制,这可以在一年内节省超过 3600 美元。

作者,
姓名:mahinur ra​​hman
联系方式:dev.mahinur.rahman@gmail.com

卓越飞翔博客
上一篇: React 设计模式~容器组件/不受控制的受控组件~
下一篇: 在 Python 中使用标准化剪切 (NCut) 进行无监督图像分割的指南
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏