Unumdorlik va kuzatuvchanlik
Hisobot sahifasi noutbukda 0,2 soniyada ochiladi, productionda esa 9 soniya. Kod bir xil. Nega?
Javob bermasdan oldin farq qayerdan kelishini taxmin qiling: kodmi, ma’lumotmi, servermi?
Bu ma’ruza oxirida siz quyidagilarni bajara olasiz...
with(), load(), withCount() va Model::preventLazyLoading()EXPLAIN ANALYZE bilan tekshirishniCache::remember, teglar va keshni bekor qilish (invalidation)/up va kengaytirilgan tekshiruvlar) va Sentry orqali xatolar monitoringiniUnumdorlik va kuzatuvchanlik asoslari
Tizim ichini ko‘rish: uch ustun
Loglar
order.confirmed + order_id, user_id.Metrikalar
Treyslar
Profillash
O‘rtacha emas, p95 ga qarang
<?php function persentil(array $ms, int $p): int { sort($ms); $rank = (int) ceil($p / 100 * count($ms)); return $ms[max($rank, 1) - 1]; } $vaqtlar = [120, 95, 110, 2300, 130, 105, 98, 140, 115, 101, 125, 99, 135, 1800, 108, 112, 97, 118, 122, 103]; printf("O‘rtacha: %d ms\n", array_sum($vaqtlar) / count($vaqtlar)); printf("p50: %d ms\n", persentil($vaqtlar, 50)); printf("p95: %d ms\n", persentil($vaqtlar, 95)); printf("p99: %d ms\n", persentil($vaqtlar, 99));
O‘rtacha: 306 ms p50: 112 ms p95: 1800 ms p99: 2300 ms
Debugbar va Telescope — faqat dev uchun
# sahifa pastidagi panel: SQL, vaqt, xotira, modellar composer require barryvdh/laravel-debugbar --dev # alohida /telescope sahifasi: so'rovlar, job, kesh, log composer require laravel/telescope --dev php artisan telescope:install php artisan migrate # .env (faqat lokal!) # APP_DEBUG=true DEBUGBAR_ENABLED=true TELESCOPE_ENABLED=true
Debugbar → Queries: 103 statements, 100 duplicates Debugbar → Timeline: Application 2.41 s Debugbar → Models: Order 50, Counterparty 50, OrderItem 150
require-dev ga yoziladi; composer install --no-dev uni o‘rnatmaydiAPP_DEBUG=false; profiler paneli hech qachon ochiq bo‘lmaydi1-bo‘lim yakuni: Unumdorlik va kuzatuvchanlik asoslari
N+1 muammosi va eager loading
51 ta so‘rov yoki 2 ta so‘rov
<?php function sorovlar(int $n, bool $eager): array { $log = ["select * from orders limit $n"]; if ($eager) { $ids = implode(', ', range(1, $n)); $log[] = "select * from counterparties where id in ($ids)"; return $log; } foreach (range(1, $n) as $id) { $log[] = "select * from counterparties where id = $id"; } return $log; } printf("Lazy (n=50): %d ta so‘rov\n", count(sorovlar(50, false))); printf("Eager (n=50): %d ta so‘rov\n", count(sorovlar(50, true))); $s = sorovlar(3, true); echo $s[1], "\n";
Lazy (n=50): 51 ta so‘rov Eager (n=50): 2 ta so‘rov select * from counterparties where id in (1, 2, 3)
with(), load(), withCount() — OrderController
public function index(): View { $orders = Order::query() ->with([ 'counterparty:id,name,inn', 'warehouse:id,code', 'items.product:id,sku,name', ]) ->withCount('items') ->withSum('items', 'total') ->latest() ->paginate(50); return view('orders.index', compact('orders')); } // model allaqachon bor bo'lsa: // $order->loadMissing('items.product');
select * from orders order by created_at desc limit 50 offset 0 select id, name, inn from counterparties where id in (3, 7, 12, ...) select id, code from warehouses where id in (1, 2) select * from order_items where order_id in (101, 102, ...) select id, sku, name from products where id in (5, 9, 14, ...)
id albatta bo‘lsinorder_items, keyin productsitems_count atributi — subquery orqali, alohida so‘rovsizitems_sum_total — yig‘indi ham shu so‘rovdacount(*) bilan 6 ta).Lazy loading’ni dev muhitda taqiqlash
// app/Providers/AppServiceProvider.php public function boot(): void { // lazy loading -> LazyLoadingViolationException Model::preventLazyLoading(); // productionda sahifa buzilmasin: istisno o'rniga log if ($this->app->isProduction()) { Model::handleLazyLoadingViolationUsing( function (Model $model, string $relation): void { Log::warning('lazy_loading', [ 'model' => $model::class, 'relation' => $relation, ]); }); } }
Illuminate\Database\LazyLoadingViolationException Attempted to lazy load [counterparty] on model [App\Models\Order] but lazy loading is disabled.
APP_ENV=production bo‘lsa true$fillable dan tashqari maydonni ham taqiqlaydiModel::preventLazyLoading(! $this->app->isProduction()); — productionda tekshiruv umuman o‘chadi.count so‘rovini hisobga olmang).2-bo‘lim yakuni: N+1 muammosi va eager loading
with() va load() ning farqi nimada?$order->items()->count() o‘rniga nima yozish kerak?1-topshiriq: N+1: nechta SQL so‘rov?
Sahifada $n ta buyurtma chiqariladi (1 ta asosiy so‘rov). $ishlatiladi — har bir buyurtma uchun murojaat qilinadigan munosabatlar (har biri belongsTo), $eager — with() ga berilgan munosabatlar. Eager yuklangan har bir munosabat (ishlatilmasa ham) $n > 0 bo‘lsa 1 ta so‘rov qo‘shadi, $n = 0 bo‘lsa — 0 ta (Eloquent bo‘sh natija uchun eager so‘rov yubormaydi). Eager yuklanmagan, lekin ishlatilgan har bir munosabat $n ta so‘rov qo‘shadi (lazy loading). Takrorlangan nomlar bir marta hisoblanadi. $n < 0 bo‘lsa — InvalidArgumentException.
Imzo: function sorovlar_soni(int $n, array $ishlatiladi, array $eager): int
Qaytaradi: int — sahifa yuboradigan SQL so‘rovlar soni.
sorovlar_soni(50, ['counterparty', 'warehouse'], [])
101
Indekslar va so‘rov rejasi
Indeks — tartiblangan “mundarija”
B-tree
=, in, >, between, order by, like 'UN-%' uchun.Kompozit
(status, created_at). Tartib muhim — chap prefiks qoidasi.Unique
sku, (warehouse_id, product_id) — cheklov va indeks bir vaqtda.Narxi
insert/update indekslarni ham yangilaydi; disk joyi ketadi.counterparty_id, order_id ga o‘zingiz qo‘shing.OmborPro uchun indekslar
return new class extends Migration { public function up(): void { Schema::table('orders', function (Blueprint $table) { $table->index(['status', 'created_at']); $table->index('counterparty_id'); }); Schema::table('stock_movements', function (Blueprint $t) { $t->index(['product_id', 'created_at']); }); Schema::table('invoices', function (Blueprint $table) { $table->index(['status', 'due_at']); }); } };
INFO Running migrations. 2026_10_27_100000_add_performance_indexes ........ 184ms DONE -- yaratilgan indekslar: orders_status_created_at_index, -- orders_counterparty_id_index, invoices_status_due_at_index ...
join va eager loading in (...) uchunjadval_ustun1_ustun2_indexSeq Scan → Index Scan
EXPLAIN (ANALYZE, COSTS OFF) SELECT id, number, total FROM orders WHERE status = 'confirmed' AND created_at >= '2026-10-01' ORDER BY created_at DESC LIMIT 50;
-- indeks yo'q (200 000 qator): Seq Scan on orders (actual time=0.02..39.5 rows=4210 loops=1) Rows Removed by Filter: 195790 Execution Time: 41.9 ms -- (status, created_at) indeksi bilan: Index Scan Backward using orders_status_created_at_index on orders Execution Time: 0.2 ms
update/delete uchun ehtiyot bo‘lingorder by created_at desc ham indeks tartibidan olinadi, Sort yo‘qOrder::where(...)->explain() yoki ->toRawSql() bilan SQL’ni olib psql’da ishga tushiring.Indeks bor, lekin ishlamaydi
| Holat | Nega ishlamaydi | Yechim |
|---|---|---|
whereRaw('date(created_at) = ?') | ustunga funksiya qo‘llangan | whereBetween('created_at', [$kun, $ertasi]) |
like '%001' | boshida % — tartib foydasiz | prefiks qidiruv like 'UN-%' yoki to‘liq matnli qidiruv |
Indeks (status, created_at), so‘rov faqat created_at bo‘yicha | chap prefiks yo‘q | alohida created_at indeksi yoki tartibni o‘zgartirish |
where is_active = true (95 % qator) | selektivlik past — Seq Scan arzonroq | indeks qo‘ymang yoki qisman indeks |
where inn = 123456789 (ustun varchar) | tur mos emas — almashtirish kerak | qiymatni satr sifatida bering |
CREATE INDEX ... ON invoices (due_at) WHERE status <> 'paid' — migratsiyada DB::statement() bilan.3-bo‘lim yakuni: Indekslar va so‘rov rejasi
(status, created_at) indeksi where created_at >= ? so‘roviga nega yordam bermaydi?EXPLAIN ANALYZE natijasida qaysi qatorlar indeks yetishmasligini ko‘rsatadi?foreignId()->constrained() indeks yaratadimi?2-topshiriq: Kompozit indeksning chap prefiksi
Kompozit B-tree indeks ustunlari $indeks (tartib bilan) va so‘rov shartlari $shartlar (ustun => operator) berilgan. Indeks ustunlarini chapdan o‘ngga ko‘rib chiqing: ustun shartlarda bo‘lmasa — to‘xtang; operator tenglik (=, in) bo‘lsa — ustun hisoblanadi va davom etiladi; oraliq (>, <, >=, <=, between) bo‘lsa — ustun hisoblanadi va to‘xtatiladi. Shartlarda boshqa operator bo‘lsa (masalan, like) — InvalidArgumentException.
Imzo: function indeks_ustunlari(array $indeks, array $shartlar): int
Qaytaradi: int — so‘rovda indeksdan foydalaniladigan ustunlar soni (0 dan indeks uzunligigacha).
indeks_ustunlari(['status', 'created_at'], ['status' => '=', 'created_at' => '>='])
2
Redis bilan keshlash
remember(): HIT va MISS
<?php function remember(array &$c, string $k, int $ttl, int $now, callable $fn): array { if (isset($c[$k]) && $c[$k]['exp'] > $now) { return [$c[$k]['v'], 'HIT']; } $c[$k] = ['v' => $fn(), 'exp' => $now + $ttl]; return [$c[$k]['v'], 'MISS']; } $cache = []; $hisobot = fn () => array_sum([1200000, 850000, 430000]); foreach ([0, 100, 599, 600, 700] as $t) { [$v, $h] = remember($cache, 'report:sales:2026-10', 600, $t, $hisobot); echo "t={$t}s {$h} {$v}\n"; }
t=0s MISS 2480000 t=100s HIT 2480000 t=599s HIT 2480000 t=600s MISS 2480000 t=700s HIT 2480000
Hisobotni teglar bilan keshlash
public function monthlySales(string $month, int $whId): array { $key = "report:sales:v1:{$month}:wh={$whId}"; $tags = ['reports', "warehouse:{$whId}"]; return Cache::tags($tags)->remember($key, now()->addMinutes(10), fn () => Order::query() ->where('warehouse_id', $whId) ->where('status', OrderStatus::Shipped) ->whereBetween('created_at', $this->monthRange($month)) ->selectRaw('date(created_at) as day, sum(total) as sum') ->groupBy('day') ->pluck('sum', 'day') ->all()); }
1-chaqiruv: MISS → 3 ta SQL, 640 ms 2-chaqiruv: HIT → 0 ta SQL, 2 ms (Redis GET)
reports yoki bitta ombor bo‘yicha tozalash mumkinfile va database drayverlarida ishlamaydi: .env da CACHE_STORE=redis.Ma’lumot o‘zgarsa — keshni tozalash
// app/Listeners/FlushReportCache.php class FlushReportCache { public function handle(OrderConfirmed $event): void { $whId = $event->order->warehouse_id; Cache::tags(["warehouse:{$whId}"])->flush(); } } // stampede himoyasi: bir vaqtda faqat bitta jarayon hisoblaydi $data = Cache::lock("lock:report:{$month}", 10) ->block(5, fn () => $reports->monthlySales($month, 1)); // .env // CACHE_STORE=redis REDIS_HOST=redis REDIS_CLIENT=phpredis
OrderConfirmed(BY-2026-000123, warehouse_id=1) → Cache::tags(['warehouse:1'])->flush() → keyingi hisobot so'rovi: MISS, yangi raqamlar
4-bo‘lim yakuni: Redis bilan keshlash
3-topshiriq: Hisobot uchun kesh kaliti
Hisobot nomi $hisobot va parametrlar $params dan barqaror kesh kalitini yasang: omborpro:report:<hisobot>:<qism>. Parametrlar kalit bo‘yicha alifbo tartibida (ksort, SORT_STRING), null qiymatlilar tashlab yuboriladi, true/false → 1/0, massiv qiymat o‘sish tartibida saralanib vergul bilan qo‘shiladi; juftliklar kalit=qiymat ko‘rinishida & bilan birlashtiriladi. Parametr qolmasa, qism — all. Hisobot nomi ^[a-z][a-z_]*$ ga mos kelmasa — InvalidArgumentException.
Imzo: function kesh_kaliti(string $hisobot, array $params): string
Qaytaradi: string — masalan, omborpro:report:sales:from=2026-10-01&to=2026-10-31&warehouse_id=3.
kesh_kaliti('sales', ['to' => '2026-10-31', 'from' => '2026-10-01', 'warehouse_id' => 3])"omborpro:report:sales:from=2026-10-01&to=2026-10-31&warehouse_id=3"
Strukturali loglash
Log + kontekst va request_id
// app/Http/Middleware/AssignRequestId.php public function handle(Request $request, Closure $next): Response { $id = $request->header('X-Request-Id') ?: (string) Str::uuid(); Context::add('request_id', $id); $response = $next($request); $response->headers->set('X-Request-Id', $id); return $response; } // app/Services/OrderService.php public function logConfirmed(Order $order): void { Log::info('order.confirmed', [ 'order_id' => $order->id, 'number' => $order->number, 'total' => $order->total, 'user_id' => auth()->id(), ]); }
[2026-10-27 10:15:02] production.INFO: order.confirmed
{"order_id":123,"number":"BY-2026-000123","total":"1500000.00",
"user_id":7} {"request_id":"9b2f6c1e-..."}config/logging.php: JSON formatdagi kanal
use Monolog\Formatter\JsonFormatter; use Monolog\Handler\StreamHandler; return [ 'default' => env('LOG_CHANNEL', 'stack'), 'channels' => [ 'stack' => ['driver' => 'stack', 'channels' => explode(',', env('LOG_STACK', 'single'))], 'json' => [ 'driver' => 'monolog', 'level' => env('LOG_LEVEL', 'info'), 'handler' => StreamHandler::class, 'handler_with' => ['stream' => 'php://stderr'], 'formatter' => JsonFormatter::class, ], // single, daily, stderr ... standart kanallar ], ];
{"message":"order.confirmed","context":{"order_id":123,
"total":"1500000.00"},"level":200,"level_name":"INFO",
"channel":"production","datetime":"2026-10-27T10:15:02.123456+05:00",
"extra":{"request_id":"9b2f6c1e-..."}}.env: LOG_CHANNEL=stack, LOG_STACK=daily,json, LOG_LEVEL=info. Natijadagi level: 200 — Monolog’da INFO.Logga yozishdan oldin niqoblash
<?php function logLine(string $level, string $msg, array $ctx): string { $secret = ['password', 'token', 'card_number']; foreach ($ctx as $k => $v) { if (in_array($k, $secret, true)) { $ctx[$k] = '***'; } elseif ($k === 'phone') { $ctx[$k] = substr($v, 0, 6) . '*****' . substr($v, -2); } } return json_encode(['level' => strtoupper($level), 'message' => $msg, 'context' => $ctx]); } echo logLine('warning', 'payment.failed', [ 'invoice_id' => 45, 'method' => 'payme', 'token' => 'tok_abc123', 'phone' => '+998901234567', ]), "\n";
{"level":"WARNING","message":"payment.failed","context":{"invoice_id":45,"method":"payme","token":"***","phone":"+99890*****67"}}tap sozlamasi orqali barcha loglarga qo‘llash mumkin.5-bo‘lim yakuni: Strukturali loglash
LOG_LEVEL=debug qo‘yish nega yomon?Health check va Sentry
/up marshruti va o‘z tekshiruvlarimiz
// bootstrap/app.php return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', api: __DIR__.'/../routes/api.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) // ... ->create(); // AppServiceProvider::boot() Event::listen(function (DiagnosingHealth $event) { DB::select('select 1'); Cache::store('redis')->put('health:ping', now()->timestamp, 60); });
$ curl -s -o /dev/null -w "%{http_code}\n" https://omborpro.test/up
200
# PostgreSQL to'xtatilganda:
500/up chaqirilganda yuboriladigan hodisa/up — Docker healthcheck va uptime monitor uchun yengil tekshiruv; og‘ir so‘rovlar qo‘ymang./health: JSON javob va 503
Route::get('/health', function () { $check = function (callable $fn): array { $t = microtime(true); $ok = rescue(fn () => $fn() !== false, false, false); $ms = (int) round((microtime(true) - $t) * 1000); return ['ok' => $ok, 'ms' => $ms]; }; $checks = [ 'database' => $check(fn () => DB::select('select 1')), 'redis' => $check(fn () => Redis::ping()), 'queue' => $check(fn () => Queue::size('default') < 1000), ]; $fail = ! $checks['database']['ok'] || ! $checks['redis']['ok']; $all = ! in_array(false, array_column($checks, 'ok'), true); $status = $fail ? 'fail' : ($all ? 'ok' : 'degraded'); $code = $fail ? 503 : 200; return response()->json(compact('status', 'checks'), $code); });
HTTP/1.1 200 OK
{"status":"degraded","checks":{"database":{"ok":true,"ms":3},
"redis":{"ok":true,"ms":1},"queue":{"ok":false,"ms":2}}}false qaytaradi, report qilmaydifail va 503degraded: ishlayapti, lekin ogohlantirish->middleware('throttle:30,1') qo‘shib, uni ortiqcha chaqiruvlardan himoyalang.ok · degraded · fail
<?php $checks = [ 'database' => ['ok' => true, 'critical' => true], 'redis' => ['ok' => true, 'critical' => true], 'queue' => ['ok' => false, 'critical' => false], ]; $failed = array_keys(array_filter($checks, fn ($c) => !$c['ok'])); $critical = array_filter($failed, fn ($n) => $checks[$n]['critical']); $status = match (true) { $critical !== [] => 'fail', $failed !== [] => 'degraded', default => 'ok', }; $http = $status === 'fail' ? 503 : 200; echo "HTTP $http\n"; echo json_encode(['status' => $status, 'failed' => $failed]), "\n";
HTTP 200
{"status":"degraded","failed":["queue"]}degraded da trafik to‘xtatilmaydi, faqat ogohlantirish beriladiXatolar monitoringi: o‘rnatish va sozlash
// composer require sentry/sentry-laravel // php artisan sentry:publish --dsn=https://KEY@sentry.example.uz/1 // bootstrap/app.php use Illuminate\Foundation\Configuration\Exceptions; use Sentry\Laravel\Integration; return Application::configure(basePath: dirname(__DIR__)) // ->withRouting(...)->withMiddleware(...) ->withExceptions(function (Exceptions $exceptions) { Integration::handles($exceptions); }) ->create(); // .env // SENTRY_LARAVEL_DSN=https://KEY@sentry.example.uz/1 // SENTRY_TRACES_SAMPLE_RATE=0.2 // SENTRY_SEND_DEFAULT_PII=false
$ php artisan sentry:test [Sentry] DSN discovered! [Sentry] Sending test event... [Sentry] Event sent with ID: 3f1c...e9
.env da, repozitoriyga yozilmaydi.6-bo‘lim yakuni: Health check va Sentry
/up marshrutiga o‘z tekshiruvingizni qanday qo‘shasiz?Asosiy xulosalar
1Avval o‘lcha
2N+1 → eager loading
with(), load(), withCount(); dev muhitda Model::preventLazyLoading().3Indeks — so‘rov uchun
EXPLAIN ANALYZE bilan tekshiring.4Kesh + invalidation
flush(); teglar uchun Redis kerak.5Strukturali log
request_id; maxfiy ma’lumotlar yo‘q.6Health check va Sentry
/up + DiagnosingHealth, JSON /health (503), Sentry bilan xatolar monitoringi.Yakunlashdan oldin sakkizta savol
with() siz chiqarilsa, nechta so‘rov ketadi?withCount('items') qaysi atributni qo‘shadi?Model::preventLazyLoading() qachon istisno tashlaydi?(status, created_at) indeksi qaysi so‘rovga mos: where status = ? yoki where created_at > ??EXPLAIN ANALYZE dagi Seq Scan nimani anglatadi?Cache::tags() ishlashi uchun qaysi drayver kerak?13-amaliy mashg‘ulot: 5 ta PHP topshiriq va loyiha bosqichi
Apdex: foydalanuvchi qoniqishi
Strukturali log yozuvi va niqoblash
Health check holatini hisoblash
Teglar va TTL bilan kesh
Takroriy so‘rovlarni aniqlash (N+1 detektori)
Darsni tark etishdan oldin
Javoblaringizni yozing (✎ Javob yozish) yoki qog‘ozga yozib topshiring.
Cache::remember('report', 600, ...) kalitida qanday xato bor va uni qanday tuzatasiz?request_id yordamida sababni qanday topasiz?