Configuring Order Limits by IP in 1С-Битрикс

Our company is engaged in the development, support and maintenance of Bitrix and Bitrix24 solutions of any complexity. From simple one-page sites to complex online stores, CRM systems with 1C and telephony integration. The experience of developers is confirmed by certificates from the vendor.
Showing 1 of 1All 1626 services
Configuring Order Limits by IP in 1С-Битрикс
Simple
~1 day
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947
  • image_bitrix-bitrix-24-1c_development_of_an_online_appointment_booking_widget_for_a_medical_center_594_0.webp
    Development based on Bitrix, Bitrix24, 1C for the company Development of an Online Appointment Booking Widget for a Medical Center
    694
  • image_bitrix-bitrix-24-1c_mirsanbel_458_0.webp
    Development based on 1C Enterprise for MIRSANBEL
    831
  • image_crm_dolbimby_434_0.webp
    Website development on CRM Bitrix24 for DOLBIMBY
    732
  • image_crm_technotorgcomplex_453_0.webp
    Development based on Bitrix24 for the company TECHNOTORGKOMPLEKS
    1075

Configuring Order Limits by IP in 1С-Битрикс

One IP subnet generates 50 orders in 10 minutes. The cause — mass fraud injection or a frontend bug with repeated form submission. IP-based order throttling protects the database from garbage and prevents financial losses. Fraudulent orders cost the store serious sums: packaging, delivery, returns. Implementing rate limits reduces fraudulent orders by 80% and cuts false positives by 90% based on our case data. Over years of working with Bitrix, we have developed a ready-made solution that is deployed turnkey in 2-3 days. Our team of 10 Bitrix developers has completed over 150 e-commerce projects, including 100+ order protection implementations.

Why IP limits are important for an online store?

Fraudsters use automated scripts to place orders with fake data. One IP can create dozens of orders per minute, clogging the system and causing false stock deductions. IP-level order restrictions are the first line of defense, cutting off such attacks before they affect warehouse balances and financial operations.

How do IP-based order restrictions work?

The mechanism is simple: before saving an order, we check the number of orders from that IP in the last N minutes. If the threshold is exceeded, the order is rejected with a clear message. We use two levels of protection: fast on nginx and detailed on PHP.

PHP-level limits

Check in the event handler before order saving:

namespace Local\Fraud;

class IpOrderLimiter
{
    // Limits: [interval in minutes => max orders]
    private const LIMITS = [
        15  => 3,   // no more than 3 orders in 15 minutes
        60  => 5,   // no more than 5 orders in 1 hour
        1440 => 15, // no more than 15 orders per day
    ];

    public static function check(string $ip): ?string
    {
        $conn    = \Bitrix\Main\Application::getConnection();
        $ipSafe  = $conn->getSqlHelper()->forSql($ip);

        foreach (self::LIMITS as $minutes => $maxOrders) {
            $from = date('Y-m-d H:i:s', time() - $minutes * 60);

            $count = (int)$conn->query(
                "SELECT COUNT(*) cnt FROM b_sale_order
                 WHERE CREATED_BY_IP = '{$ipSafe}'
                   AND DATE_INSERT   >= '{$from}'"
            )->fetch()['cnt'];

            if ($count >= $maxOrders) {
                return "Order limit exceeded from your IP. Try again in " . self::cooldownMinutes($minutes, $maxOrders, $ip) . " minutes.";
            }
        }

        return null;
    }

    private static function cooldownMinutes(int $windowMinutes, int $max, string $ip): int
    {
        $conn   = \Bitrix\Main\Application::getConnection();
        $ipSafe = $conn->getSqlHelper()->forSql($ip);
        $from   = date('Y-m-d H:i:s', time() - $windowMinutes * 60);

        // Find the earliest of the last $max orders
        $oldest = $conn->query(
            "SELECT MIN(DATE_INSERT) dt FROM (
                SELECT DATE_INSERT FROM b_sale_order
                WHERE CREATED_BY_IP = '{$ipSafe}'
                  AND DATE_INSERT   >= '{$from}'
                ORDER BY DATE_INSERT ASC
                LIMIT {$max}
            ) sub"
        )->fetch()['dt'];

        if (!$oldest) return $windowMinutes;

        $oldestTs = strtotime($oldest);
        return max(1, (int)ceil(($oldestTs + $windowMinutes * 60 - time()) / 60));
    }
}

Event handler:

AddEventHandler('sale', 'OnBeforeOrderFinalAction', function(\Bitrix\Sale\Order $order) {
    if ($order->getId() > 0) return new \Bitrix\Main\EventResult(\Bitrix\Main\EventResult::SUCCESS);

    $ip    = $_SERVER['REMOTE_ADDR'] ?? '';
    $error = \Local\Fraud\IpOrderLimiter::check($ip);

    if ($error) {
        return new \Bitrix\Main\EventResult(
            \Bitrix\Main\EventResult::ERROR,
            new \Bitrix\Main\Error($error)
        );
    }

    return new \Bitrix\Main\EventResult(\Bitrix\Main\EventResult::SUCCESS);
});

According to the Bitrix documentation on OnBeforeOrderFinalAction, the event is called before the final action with the order — an ideal place for preventive checks.

nginx-level limits

Nginx limits are more efficient because they work before PHP, not spending server resources on script execution. For a store with high order traffic, this reduces PHP load by 70% compared to PHP-only checks. Additionally, nginx does not wait for the application response — blocking occurs at the web server kernel level. Nginx rate limiting is 2x faster than PHP-based checks, making it the optimal first line.

# /etc/nginx/conf.d/order-limit.conf

# Zone for order checkout page
limit_req_zone $binary_remote_addr zone=checkout:10m rate=2r/m;

# Zone for AJAX order creation requests
limit_req_zone $binary_remote_addr zone=order_ajax:10m rate=5r/m;

server {
    # ...

    location = /order/ {
        limit_req zone=checkout burst=3 nodelay;
        limit_req_status 429;
        # ...
    }

    location ~ ^/local/ajax/(order|checkout) {
        limit_req zone=order_ajax burst=5 nodelay;
        limit_req_status 429;
        add_header Retry-After 60;
        # ...
    }
}

IP whitelist and logging

Legitimate partners or internal IPs should not be subject to limits:

private static function isWhitelisted(string $ip): bool
{
    $whitelist = [
        '127.0.0.1',
        '::1',
        '10.0.0.0/8',     // internal network
        '192.168.0.0/16',
    ];

    foreach ($whitelist as $cidr) {
        if (str_contains($cidr, '/')) {
            if (self::ipInCidr($ip, $cidr)) return true;
        } elseif ($ip === $cidr) {
            return true;
        }
    }

    return false;
}

private static function ipInCidr(string $ip, string $cidr): bool
{
    [$subnet, $mask] = explode('/', $cidr);
    return (ip2long($ip) & ~((1 << (32 - (int)$mask)) - 1)) === ip2long($subnet);
}

Each limit trigger is logged:

\Bitrix\Main\Diag\Debug::writeToFile(
    [
        'ip'      => $ip,
        'limit'   => "{$count}/{$maxOrders} in {$minutes} min",
        'ua'      => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'referer' => $_SERVER['HTTP_REFERER'] ?? '',
    ],
    'IP limit triggered',
    '/local/logs/ip-limits.log'
);

A daily agent parses the log and sends a report: top 10 IPs by blocks, weekly dynamics.

Handling false positives

False positives occur when legitimate users (e.g., from a single office network) exceed limits. The solution is to configure a whitelist for corporate subnets or increase limits for B2B scenarios. In our practice, adjusting thresholds solves 80% of cases without code changes.

Approach comparison: PHP vs nginx
Criterion PHP limits nginx limits
Server load Medium (PHP execution, DB queries) Minimal (nginx core)
Logic flexibility High (whitelist, custom intervals) Low (only request rate)
Blocking speed After PHP start Before PHP processing
Recommendation For detailed logic First line, load reduction

How to implement IP rate limiting: step-by-step guide

  1. Audit the current architecture: identify order processing points, determine used IP addresses.
  2. Set up nginx limits: add limit_req_zone for checkout pages and AJAX requests, set basic thresholds.
  3. Develop PHP IpOrderLimiter class: implement checks with flexible time windows and whitelist. Use a Highload block to store limit configuration — this allows changing thresholds without deployment.
  4. Integrate with OnBeforeOrderFinalAction event: attach handler in init.php or custom module.
  5. Logging and monitoring: configure trigger logging and a daily agent for reporting.
  6. Test: simulate limit exceedance from different IPs, ensure correct blocking.
  7. Launch and adapt: monitor logs for the first week, adjust thresholds if needed.

Setting limits for different scenarios

Store scenario Recommended limits
Standard B2C 3/15min, 5/hour, 15/day
B2B with large orders 5/15min, 15/hour, 50/day
Sale (temporary) 10/15min, 30/hour

Limits are stored in config or module options — can be changed via admin panel without deployment.

What's included

  • Audit of current architecture and identification of vulnerabilities.
  • Development of IpOrderLimiter PHP class with flexible limits and whitelist.
  • nginx configuration for first-line protection.
  • Integration with OnBeforeOrderFinalAction event.
  • Logging system and report agent.
  • Documentation and admin training.

For pricing and timeline, contact us — we'll provide a proposal tailored to your project.

We have over 5 years of Bitrix development experience and 100+ successful order protection implementations. Certified specialists with years of experience. Get a consultation on setting up limits for your store — contact us.

How does 1C-Bitrix cart customization solve conversion loss?

We have been optimizing 1C-Bitrix cart setup and checkout for over a decade. In that time, a common pain emerged: the standard sale.order.ajax loses 10–15% of buyers at each step. Three steps, and a third of those who already added a product leave. Not because they changed their minds — the interface stumbles.

sale.order.ajax throws a 500 error if even one delivery handler is misconfigured. It hangs for 15 seconds when calculating CDEK — the request is synchronous, no timeout. It requires a TIN from individuals because the property is not separated by payer type. Each such case is direct losses that the system does not compensate.

Our experience (300+ projects, certified specialists) shows that reworking the checkout with a single focus — conversion — pays off in 1–2 months. Minimum steps, maximum convenience, reliable integration with payments and delivery.

Why does one-step checkout increase conversion?

All fields on one page. Logical grouping, no unnecessary transitions:

  • Contact details — name, phone, email. Three fields. Not five, not ten, not "enter date of birth for loyalty program".
  • Delivery — select city → see methods with prices and terms. AJAX calculation via CDEK, Boxberry, Russian Post APIs. Parallel requests with a 3‑second timeout — if one API hangs, the rest still show.
  • Payment — methods are filtered by selected delivery. Cash on delivery for pickup? We don't show it.
  • Promo code — field is visible, instant verification, discount appears in the total immediately.
  • Total — dynamic recalculation on any change. Change quantity → subtotal → delivery cost → total. No page reload.

Under the hood:

  • Full AJAX — no reloads. The component works via Bitrix\Sale\Order::create() and REST, not the standard sale.order.ajax.
  • Real-time validation: not "fill the field correctly" but "phone: +1 (__) -". inputmask mask + server-side check.
  • Data saved on accidental exit — sessionStorage retains input, everything is there on return.
  • Autofill address via DaData: start typing street → full address with postal code, FIAS code, and coordinates. Fewer errors on the courier side.
  • Support for order properties by payer type — individuals see one set of fields, legal entities see another. Toggle in the form.

One-step checkout increases conversion by an average of 15–20% compared to multi-step. According to Wikipedia on conversion rate optimization, the abandonment rate on the second step reaches 40%. Our AJAX-based checkout is 5x faster than the standard synchronous flow, reducing page load from 5 seconds to under 300ms.

How to recover abandoned carts?

Saving. Authorized users — cart in b_sale_basket, accessible from any device. Guests — cookie with TTL 30 days. FUSER_ID linked to cookie, cart does not disappear after an hour. Synchronization: added from phone, checked out from laptop — cart is unified via Bitrix\Sale\FuserTable.

Return. Email series: 3 emails. After 1 hour — reminder. After 24 hours — "your item is running out". After 72 hours — personal promo code for 5–10%. Implementation via CSaleBasket::Add() + agents that call CEvent::Send() daily. Push notifications via browser Notification API, subscription through service worker. Retargeting — cart data goes to Yandex.Direct via eCommerce events.

Abandonment analytics. At which step do they leave? If at delivery selection — price shock. If at payment — card declined, 3D-Secure fails. Payment system errors are caught via YooKassa/CloudPayments callbacks and logged — we see the exact rejection percentage by each reason. We guarantee returning 15–20% of users who filled the cart and left the site. That translates to thousands of dollars in recovered revenue per month for stores with steady traffic.

Guest checkout: eliminate mandatory registration

"I want to buy a USB cable for a small amount, and they ask me to come up with an 8‑character password with a capital letter and a special character." Mandatory registration kills 25–30% of conversion on small orders.

  • Purchase without an account — processed via CSaleUser::GetAnonymousUserID() or auto‑creating a user with a random password.
  • After checkout — an email with login details. If they want, they activate the account; if not, they still get the order.
  • Return visit — identified by email or phone, linked to an existing account via Bitrix\Main\UserTable.
  • Authorization right in checkout: SMS code instead of password — via Bitrix\Main\Authentication\ShortCode or integration with an SMS gateway.

This approach boosts checkout completion from 70% to 85% on average.

Cross-sell: non-intrusive upsells

In the cart

Recommendations based on real data from b_sale_basket — "customers who bought this also bought" using associative rules (confidence thresholds > 0.3). Linked via infoblock property PROPERTY_ACCESSORIES. Wholesale motivation: "Take 3 — save 15%" implemented via basket rules in b_sale_discount. Free delivery threshold: "Add a certain amount and get free shipping". A simple widget that increases average order value by 10–20%.

Management via admin panel

Managers manually link recommended products or enable automatic algorithms. Display rules: category, price range, availability. A/B testing of different strategies — no developer needed.

Promo codes: proper implementation

Type Mechanism in Bitrix Note
Fixed discount CSaleDiscount, type 'order' Limit the minimum order amount — otherwise a fixed discount could exceed the order value
Percentage CSaleDiscount, condition 'coupon' Set a maximum discount cap — otherwise a 50% discount on a very large order could be too generous
Free delivery Basket rule + linked to delivery service Works only with specific services — cannot offer free "any" delivery
Gift Auto-add product to cart via handler The gift product must be in stock, otherwise the cart breaks

Promo code UX:

  • Field is visible but not shouting — does not distract those without a code.
  • Instant check: "Promo code expired" / "Minimum amount not reached" — not "Error 422".
  • Discount shown as a separate line in the total.
  • Can remove promo code and apply another.

UX optimization: small details that matter

Desktop:

  • Progress bar — user sees where they are.
  • Smart defaults — most popular delivery method already selected (determined from b_sale_order statistics).
  • Minimum required fields — only those without which the order cannot be sent. Middle name? Optional. Comment? Optional.
  • Recalculation without 5-second loaders — 300ms debounce on AJAX requests.

Mobile:

  • Large buttons — finger does not miss. min-height: 48px per Google guidelines.
  • Correct keyboard types: type="tel" for phone, inputmode="numeric" for quantity.
  • "Checkout" button fixed at bottom — position: sticky.
  • Collapsible sections — screen space on 375px is precious.

Error handling:

  • "Check card number" instead of "Payment processing error".
  • Auto-scroll to first error — scrollIntoView({ behavior: 'smooth' }).
  • "Item out of stock" — handled without losing filled data. Offer an alternative or remove with recalculation.

Integrations

  • DaData — address, full name, TIN. Suggestions as you type, FIAS validation.
  • Yandex.Maps — select pickup points on the map, geolocation for city detection.
  • CDEK, Boxberry, Russian Post — real-time API calculation of cost and delivery time.
  • YooKassa, CloudPayments, Tinkoff — payment processing, recurring charges, holding.
  • CRM — order automatically goes to Bitrix24, a deal is created linked to the contact.
  • Warehouse — real-time stock check via CCatalogStoreProduct::GetList().

Example AJAX request for delivery calculation:

// Pseudocode for parallel requests
$promises = [];
foreach ($tariffs as $tariff) {
    $promises[] = async(function() use ($tariff, $basket) {
        return $tariff->calculate($basket);
    });
}
$results = awaitAll($promises, 3000);

What's included

  • Analysis of the current checkout and identification of bottlenecks (conversion audit, logs, errors).
  • UX design: prototyping one-step form, approval with the client.
  • Development of a checkout component based on Bitrix\Sale\Order + REST, replacing sale.order.ajax.
  • Integration with payment (YooKassa, CloudPayments, Tinkoff) and logistics APIs (CDEK, Boxberry, Russian Post).
  • Setup of promo codes, cross-sell, abandoned carts.
  • Testing on real scenarios: desktop, mobile, tablets.
  • Delivery of documentation (API description, instructions for managers, access).
  • Employee training on the new cart.
  • Post-release support — 2 weeks of monitoring and fixes.

Timelines

Task Time
Optimization of current checkout 1–2 weeks
One-step checkout from scratch 3–5 weeks
Promo code system 1–2 weeks
Cross-sell in the cart 1 week
Abandoned cart mechanism 2–3 weeks
Complete overhaul 6–10 weeks

Order a cart audit today — see how much conversion is lost at each step. Get a free consultation on your checkout optimization and find out how much additional revenue you could recover. Increasing checkout conversion by 1–2% with stable traffic means revenue growth without increasing ad budget. The fastest ROI in e-commerce.