Mongoose inconsistent stock issue in the transaction which occurs randomly

export const createBill = async (req, res) => {
  const currentDate = getDate();
  const products = req.body.purchased;
  let {
    customerId,
    billId,
    transactionId,
    payment = 0,
    paymentMode,
    discount = 0,
    createdBy,
  } = req.body;

  const session = await mongoose.startSession();

  try {
    const result = await session.withTransaction(async () => {
      const previousBillId = await Counter.findOne({ name: "billId" });
      const previousTransactionId = await Counter.findOne({
        name: "transactionId",
      }).session(session);

      if (previousTransactionId.value != transactionId) {
        throw new Error("Duplicate Transaction !! Pls refresh");
      }

      if (previousBillId.value != billId) {
        console.log(previousBillId, billId, "Actual BIll Id");
        throw new Error("Duplicate bill !! Pls refresh");
      }

      const customer = await Customer.findById(customerId).session(session);
      if (!customer) {
        throw new Error("Customer not found");
      }

      let billTotal = 0;
      const items = [];
      const productBulkOperations = [];
      const loggerEntries = [];

      for (const product of products) {
        const quantity =
          product.piece +
          product.packet * product.packetQuantity +
          product.box * product.boxQuantity;
        billTotal += product.total;

        const id = new mongoose.Types.ObjectId(product.id);

        // Add product stock update operation to bulk array
        productBulkOperations.push({
          updateOne: {
            filter: { _id: id },
            update: { $inc: { stock: -quantity } },
          },
        });

        // Add logger entry
        const availableProduct = await Product.findById(id).session(session);
        if (!availableProduct) {
          throw new Error(`Product not found: ${product.name || product.id}`);
        }

        loggerEntries.push({
          name: "Billing",
          previousQuantity: availableProduct.stock,
          quantity: quantity,
          newQuantity: availableProduct.stock - quantity,
          product: availableProduct._id,
        });

        items.push({
          costPrice: availableProduct.costPrice,
          previousQuantity: availableProduct.stock,
          newQuantity: availableProduct.stock - quantity,
          product: availableProduct._id,
          quantity: quantity,
          discount: product.discount || 0,
          type: product.type,
          total: product.total,
        });
      }

      // Execute the bulk write operation for stock updates
      const bulkWriteResult = await Product.bulkWrite(productBulkOperations, {
        session,
      });

      if (bulkWriteResult.modifiedCount !== products.length) {
        throw new Error("Failed to update all product stocks");
      }

      await Logger.insertMany(loggerEntries, { session });

      billTotal = Math.ceil(billTotal + customer.outstanding - discount);

      const newBillId = await Counter.findOneAndUpdate(
        { name: "billId" },
        { $inc: { value: 1 } },
        { new: true, session }
      );

      if (!newBillId) {
        throw new Error("Error while creating bill id");
      }

      const newBill = await Bill.create(
        [
          {
            customer: customerId,
            items: items,
            total: billTotal,
            payment,
            discount,
            createdBy,
            id: newBillId.value,
          },
        ],
        { session }
      );

      if (!newBill[0]) {
        throw new Error("Unable to create the bill");
      }

      let transaction = null;
      if (payment > 0) {
        let newTransId = await Counter.findOneAndUpdate(
          { name: "transactionId" },
          {
            $inc: { value: 1 },
          },
          { new: true, session }
        );
        transaction = await Transaction.create(
          [
            {
              id: newTransId.value,
              name: customer.name,
              purpose: "Payment",
              amount: payment,
              previousOutstanding: billTotal,
              newOutstanding: billTotal - payment,
              taken: false,
              paymentMode,
              approved: true,
              customer: customer._id,
            },
          ],
          { session }
        );

        if (!transaction[0]) {
          throw new Error("Unable to create the transaction");
        }
      }

      const updatedCustomer = await Customer.findByIdAndUpdate(
        customerId,
        {
          outstanding: billTotal - payment,
        },
        { session }
      );

      if (!updatedCustomer) {
        throw new Error("Unable to update the customer's outstanding balance");
      }

      const dailyReport = await DailyReport.findOneAndUpdate(
        { date: currentDate },
        {
          $push: {
            transactions: transaction ? transaction[0]._id : null,
            bills: newBill[0]._id,
          },
        },
        { upsert: true, new: true, session }
      );

      if (!dailyReport) {
        throw new Error("Unable to update the daily report");
      }

      return {
        bill: newBill[0],
        updatedCustomer,
        dailyReport,
      };
    });

    session.endSession();

    return res.status(201).json({
      message: "Bill created successfully",
      data: result,
    });
  } catch (error) {
    console.log("Error creating bill:", error);
    return res.status(500).json({
      msg: error.message,
      success: false,
    });
  } finally {
    // if (session.inTransaction()) {
    //   console.log("I was called even when the session ended");

    //   await session.abortTransaction();
    // }
    session.endSession();
  }
};`


I am facing an issue with my billing system. Let me explain with an example:

Suppose a product initially has a stock of 10 pieces. After creating a bill for 5 pieces, the stock should update to 5. However, the issue is that sometimes, when I create a bill for the same product after half an hour (or later), the system reads the stock as 10 instead of 5.

This issue occurs randomly and not every time. I’ve implemented proper stock updates in my code and am also logging the stock changes, where the updated stock appears correct immediately after the update. Despite this, it occasionally reverts to the previous stock value when fetching the product stock for a new bill.

What could be causing this inconsistency, and how can I fix it?

It is hosted on m0 free tier is that the cause. I have been trying to figure it out from a long time. 
Your help would be appreciated