Skip to content

Add to cart is slow. After a bunch of products added to cart

I have create an custom api to add product into cart which is working fine.

FYI: I am using Amasty_rule plugin which have 11 active rules. Magento version 2.4.3

Here is the code which I am using to add product to cart.

<?php
namespace NamespaceModulenameModel;

class Addtocart implements NamespaceModulenameApiAddtocartInterface
{
    public function __construct(
        MagentoFrameworkJsonHelperData $jsonHelper,
        MagentoFrameworkAppRequestInterface $request,
        MagentoQuoteModelQuote $quote,
        MagentoCatalogApiProductRepositoryInterface $productRepository

    ) {
         $this->_request = $request;
         $this->_jsonHelper = $jsonHelper;
         $this->_quote = $quote;
         $this->productRepository = $productRepository;
    }

    public function addProduct($bodyString = null)
    { 
        $data = $this->_request_data;
        $quote = $this->_quote->loadByIdWithoutStore($data['cart_item']['quote_id']);
        try{
            $product = $this->productRepository->get($data['cart_item']['sku']);
            $quote->addProduct($product, $data['cart_item']['qty']);
            if($specialPrice) {
                $quote->getItemByProduct($product)->setCustomPrice('x.xx');
                $quote->getItemByProduct($product)->setOriginalCustomPrice('x.xx');
                
            }
            if ($quote->collectTotals()->save()) {
                $result['item_id'] =  $quote->getItemByProduct($product)->getId();
                $result['items_count'] = $quote->getItemsCount(); 
                $result['items_qty'] =  $quote->getItemsQty();
                $result['price'] = $quote->getItemByProduct($product)->getPrice();
                $result['row_total'] =  $quote->getItemByProduct($product)->getRowTotal();
                $result['net_amount'] =  $quote->getGrandTotal();
                $result['subtotal'] =  $quote->getSubtotal();
                $result['quote_id'] = $data['cart_item']['quote_id'];
            }
        } catch (Exception $e) {
            $this->_logger->error($e->getMessage()); 
            $result =  (!empty($result)) ? $result : $e->getMessage();
        }
        echo $this->_jsonHelper->jsonEncode(['status' => $code, 'response' =>  $result]); die;
    }
}

After a bunch of products add in cart. API takes time to add product in cart. e.g.

upto 10 products 2s

upto 20 products 3s to 4s

upto 30 products 4s to 5s

……….

after debug and found collectTotals is taking time.

If you guys have any Idea to optimize please share.

Any help will be appreciated.