Interview Handbook by Sayed Elmahdy English

المحور 20 · الجودة والتشغيل

Logging و Observability

Structured logging، و OpenTelemetry، و Metrics، و Traces، و Health checks، و Production debugging.

15 سؤالJunior · 3Mid · 8Senior · 410 اختيارات

المفاهيم

هنفهم إيه؟ لو الدفع بطيء، هتتعلم تحدد هل التأخير في التطبيق أو قاعدة البيانات أو خدمة خارجية، وتختار log أو metric أو يجاوب السؤال. بعد كده تربط القياس بهدف خدمة وتنبيه يساعد الفريق يتصرف قبل ما المشكلة تكبر.

قبل ما تبدأ: log يسجل حدثاً، metric تلخص قياساً عبر الزمن، وtrace تتبع رحلة request بين المكونات. هي زمن الاستجابة، و هدف معلن لمستوى الخدمة. مش مطلوب منصة مراقبة بعينها؛ الفكرة هي السؤال الذي تريد الإجابة عنه.

المصطلحات اللي تحتها خط منقّط تقدر تضغط عليها لمعرفة معناها، وترجع تكمل من نفس مكانك.

#Logs و metrics و traces: كل إشارة بتجاوب على إيه؟Logs, metrics and traces: different questions

مثال خطوة بخطوة
  1. افترض إن الدفع أخذ ثانيتين. Metric يبين عدد عمليات الدفع البطيئة خلال الفترة؛ log يسجل حدثًا محددًا مثل رفض بنك لعملية بعينها.
  2. يتابع رحلة طلب واحد: دخول ، ثم استعلام قاعدة البيانات، ثم استدعاء البنك. كل عملية ذات بداية ونهاية ، والعلاقات بينها تبيّن مكان الانتظار.
  3. لو استدعاء البنك استغرق معظم الوقت، تبدأ التحقيق هناك بدل تخمين إن قاعدة البيانات السبب. اربط السجلات بمعرف الرحلة، وخد في حسابك إن قد لا يحفظ كل رحلة.

«الدفع بطيء» مش تشخيص. محتاج تعرف حجم التأثير، وأنهي مرحلة اتأخرت، وتفاصيل الفشل. Observability هي قدرتك تستنتج حالة النظام الداخلية من إشاراته، مش مجرد تثبيت dashboard.

Metrics زي عدادات العربية، و logs زي سجل الصيانة، و trace زي مسار رحلة واحدة ومدة كل محطة.
الإشارةالسؤال والمقابل
Logsإيه اللي حصل في event محددة؟ تفاصيل غنية لكن الحجم والـ retention مكلفين.
Metricsكام request وبقد إيه و errors عبر الوقت؟ تجميع مناسب للـ alerts لكن بيفقد تفاصيل الأحداث.
TracesRequest واحدة مشت فين ووقفت قد إيه؟ spans بعلاقات parent و child، مع sampling وتكلفة تخزين.

اربط الإشارات بـ service و environment و version و trace ID. مش كل trace هيتسجل مع sampling، وغياب error log مش دليل نجاح. Telemetry نفسها محتاجة limits و redaction ومراقبة export failures.

#Structured logging و LoggerMessage و SerilogStructured logging, LoggerMessage and Serilog

لو جمّعت log كـ string، البحث عن الطلبات اللي مبلغها أكبر من حد معين هيبقى parsing. Message template بتحفظ أسماء properties وقيمها لو الـ provider بيحافظ على structure. بلاش أسماء properties متغيرة لكل request.

❌ interpolation بتفقد الـ fields
logger.LogInformation($"Order {orderId} paid {amount}");
✅ template ثابتة
logger.LogInformation("Order {OrderId} paid {Amount}", orderId, amount);
using Microsoft.Extensions.Logging;

public static partial class OrderLog
{
    [LoggerMessage(EventId = 1001, Level = LogLevel.Information,
        Message = "Order {OrderId} paid {Amount}")]
    public static partial void Paid(
        ILogger logger, Guid orderId, decimal amount);     // (1)
}
// At the call site: OrderLog.Paid(logger, orderId, amount);
// Packages: Serilog.AspNetCore and Serilog.Sinks.Console
using Serilog;

builder.Host.UseSerilog((context, configuration) => configuration
    .MinimumLevel.Information()
    .Enrich.FromLogContext()
    .WriteTo.Console());                                  // (2)
🧾 شرح الكود
  1. (1) source generator يولّد implementation لـ partial method، ويقلل و parsing في hot logging paths. الـ containing type لازم partial.
  2. (2) Serilog provider بيستقبل structured events. Console الافتراضية بتعرض text؛ لو downstream محتاج استخدم formatter مناسب. ILogger scopes و LogContext يضيفوا سياق حسب التكامل.
قبلالاختيار الأنسب
String concatenation و parsing يدويILogger templates أو LoggerMessage generated methods
كل service تعمل مختلفةProperty names و event IDs وعقد redaction مشتركة

ماتسجلش أو passwords أو card data أو request body كاملة افتراضياً. ماتعملش log لنفس exception في كل طبقة؛ سجل عند boundary اللي بتتعامل مع نتيجتها.

#Log levels و scopes و correlationLog levels, scopes and correlation

Levelاستخدام مناسب
/ Debugتفاصيل تشخيص بتتشغل لمدة محدودة؛ التكلفة والبيانات الحساسة تحت السيطرة.
Informationأحداث تشغيل مهمة متوقعة زي إتمام order.
Warningتدهور أو حدث غير متوقع قابل للتعافي، زي retry بعد transient failure.
Errorالعملية فشلت ومحتاجة تحقيق؛ مش كل validation failure.
Criticalخلل شديد يهدد استمرار الخدمة أو سلامة البيانات.

W3C traceparent بيحمل version و trace ID و parent ID و flags. كل span ليها ID مستقل، لكن spans الرحلة تشترك في trace ID. Correlation ID business ممكن يستمر عبر retries أو أيام، ومش لازم يساوي trace ID.

using System.Diagnostics;

using var scope = logger.BeginScope(new Dictionary<string, object?>
{
    ["OrderId"] = orderId,
    ["TraceId"] = Activity.Current?.TraceId.ToString() // (1)
});
logger.LogWarning("Payment confirmation is delayed"); // (2)
🧾 شرح الكود
  1. (1) Activity.Current ممكن تبقى null؛ الـ provider لازم يدعم scopes عشان fields تظهر.
  2. (2) السياق بيتضاف لكل log في الـ scope من غير إعادة كتابة IDs. بعض providers بتضيف TraceId و SpanId تلقائياً حسب الإعداد.

و HttpClient بيدعموا trace propagation، لكن messages محتاجة injection و extraction عبر أو framework. متثقش في inbound correlation header كدليل هوية؛ حدّد الطول والـ format، وماتحطش أسرار في baggage.

#OpenTelemetry: instrumentation و OTLPOpenTelemetry instrumentation and OTLP

مثال خطوة بخطوة
  1. عايز تقيس مدة CreateOrder. معناها تضيف نقطة تسجل بداية العملية ونهايتها؛ الناتج فيها اسم ومدة وخصائص محدودة.
  2. في ، ActivitySource مصدر لإنشاء spans وMeter مصدر للقياسات. هي المكتبات والإعدادات التي تجمع المصادر المختارة وتعالج بياناتها وتصدرها.
  3. Exporter يرسل البيانات باستخدام بروتوكول مثل ، وقد يرسلها إلى Collector يجمعها ويوجهها لوجهة التخزين والعرض. أداة القياس، وطريقة النقل، وقاعدة التخزين أدوار مختلفة؛ ضبط واحد لا يضبط الباقي تلقائيًا.

اربط كود التطبيق بـ standard instrumentation بدل backend معين. في .NET، ActivitySource بتنتج spans، و Meter بتنتج measurements. OpenTelemetry SDK تختار المصادر وتعمل processing و و export. OTLP بروتوكول نقل، مش database ولا dashboard.

// Packages: OpenTelemetry.Extensions.Hosting, OpenTelemetry.Exporter.OpenTelemetryProtocol,
// OpenTelemetry.Instrumentation.AspNetCore, OpenTelemetry.Instrumentation.Http,
// OpenTelemetry.Instrumentation.Runtime
using OpenTelemetry;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource.AddService("orders-api")) // (1)
    .WithTracing(tracing => tracing
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddSource("Shop.Checkout")
        .AddOtlpExporter())                                         // (2)
    .WithMetrics(metrics => metrics
        .AddAspNetCoreInstrumentation()
        .AddRuntimeInstrumentation()
        .AddMeter("Shop.Orders")
        .AddOtlpExporter());                                        // (3)
builder.Logging.AddOpenTelemetry(logging => logging.AddOtlpExporter()); // (4)
🧾 شرح الكود
  1. (1) service name تربط telemetry بالمكوّن؛ أضف version و environment كـ resource attributes من deployment configuration.
  2. (2) تختار spans والمصدر المخصص؛ من غير AddSource، spans بتاعة التطبيق مش هتتجمع بالطريقة المطلوبة.
  3. (3) metrics بتتشحن من المصادر المسجلة، ومنها runtime و custom meter.
  4. (4) logs pipeline مستقلة؛ WithTracing لوحدها مش بتصدّر ILogger events.

ظبط OTLP endpoint و protocol و و authentication حسب collector؛ config شائعة هي OTEL_EXPORTER_OTLP_ENDPOINT. Collector يقدر يعمل batching و redaction و routing. حط queue limits وراقب dropped telemetry. Export مش ضمان تخزين، وماتعملش exporters مكررة لنفس signal من غير قصد.

#Custom spans و metrics من غير cardinality explosionCustom spans and bounded-cardinality metrics

بتقول request خدت قد إيه، لكن مش بتشرح انتظار حجز المخزون. أضف span لخطوة business مهمة، و metric مجمعة لمدتها. ماتحطش order ID أو email كـ metric label: كل قيمة جديدة بتعمل time series وتكلفة.

using System.Diagnostics;
using System.Diagnostics.Metrics;

public static class OrderTelemetry
{
    public static readonly ActivitySource Source = new("Shop.Checkout");
    public static readonly Meter Meter = new("Shop.Orders");
    public static readonly Counter<long> Completed =
        Meter.CreateCounter<long>("orders.completed");           // (1)
    public static readonly Histogram<double> Duration =
        Meter.CreateHistogram<double>("orders.duration", "s"); // (2)
}

// Inside an async service method; ReserveAsync is an application operation.
using var activity = OrderTelemetry.Source.StartActivity("reserve-stock");
long started = Stopwatch.GetTimestamp();
try
{
    await ReserveAsync(ct);
    OrderTelemetry.Completed.Add(1);
}
catch (Exception ex)
{
    activity?.SetStatus(ActivityStatusCode.Error, ex.GetType().Name); // (3)
    throw;
}
finally
{
    OrderTelemetry.Duration.Record(
        Stopwatch.GetElapsedTime(started).TotalSeconds);          // (4)
}
🧾 شرح الكود
  1. (1) Counter تعد النجاحات هنا؛ الاسم والعقد يحددوا «completed» يعني حجز، مش order مدفوعة. في التطبيق الحقيقي سمّي metric حسب المرحلة أو وسّع scope للعملية كلها.
  2. (2) تخزن توزيع observations بوحدة seconds، ومنها backend يحسب percentiles.
  3. (3) StartActivity ممكن ترجع null لو مفيش listener أو مش محتاج Activity؛ ?. مهمة. المثال يسجل فشل، وسياسة cancellation المتوقعة لازم تتعامل معاها منفصل.
  4. (4) finally بتقيس النجاح والفشل؛ Stopwatch ساعة elapsed مناسبة، مش طرح DateTime.Now.

خلي ActivitySource و Meter طويلة العمر، مش واحدة لكل request. Tags زي operation و outcome محدودة القيم مناسبة للـ metrics؛ IDs للتفاصيل في logs أو بعد privacy review. Sampling أول الرحلة أرخص، و tail sampling في collector يقدر يختار traces البطيئة أو الفاشلة مقابل buffering وتكلفة.

#RED و USE و histograms و percentilesRED, USE, histograms and percentiles

مثال خطوة بخطوة
  1. رتّب مدد 100 طلب من الأسرع للأبطأ. لو نحو 95 منها عند أو أقل من 300 مللي ثانية، والبقية أبطأ، قيمة تقارب 300 حسب طريقة التقدير.
  2. المتوسط وحده ممكن يخفي الخمسة الأبطأ. يحتفظ بتوزيع المدد في نطاقات، فتقدر تسأل كام طلب دخل تحت حد معين وتقدّر percentiles.
  3. قياس مشغول بنسبة عالية اسمه utilization؛ وجود شغل منتظر CPU مثال saturation. مورد مشغول وطابور انتظار متزايد يشيران لمشكلة مختلفة عن ارتفاع الاستخدام وحده.

للخدمات: Rate و Errors و Duration. للموارد: Utilization و Saturation و Errors. CPU utilization عالية تختلف عن saturation: tasks منتظرة CPU أو connection pool queue ممكن تكشف bottleneck حتى قبل فشل الطلبات.

نوع metricمثال
Counterrequests و failures؛ احسب rate أو delta وراعي process restarts.
Gauge / observable gaugequeue depth أو قيمة آنية؛ مش مجموع عبر الزمن.
Histogramتوزيع أو payload size؛ buckets مناسبة للـ .

p95 معناها حوالي 95% من الملاحظات في النافذة أقل من أو تساوي القيمة. مش «95% من المستخدمين» بالضرورة. Average بتخبي tail latency، وماتجمعش p95 بتاعة كل instance بمتوسط؛ اجمع توزيعات compatible وبعدين احسب percentile.

Requests: 95 at 100 ms, 5 at 2000 ms                       // (1)
Mean: (95 * 100 + 5 * 2000) / 100 = 195 ms
Tail: five requests still take two seconds
SLO threshold: count requests <= 300 ms / eligible requests // (2)
🧾 شرح الكود
  1. (1) المتوسط المعقول يخفي تجربة الـ tail. حساب percentile نفسه يعتمد على estimator و buckets.
  2. (2) لو عندك threshold محدد، good-events ratio أسهل لقياس SLO بدقة من percentile متقربة.

#SLI و SLO و error budgets و alertsSLIs, SLOs, error budgets and alerts

قياس تجربة الخدمة، زي نسبة checkout ناجحة من الطلبات المؤهلة. هدف للقياس خلال نافذة، و التزام تعاقدي ممكن يكون له تبعات. عرف النجاح والاستثناءات ومصدر القياس؛ 200 ممكن تخفي payment فشلت business-wise.

SLO: 99.9% successful eligible requests over 30 days
Budget fraction: 1 - 0.999 = 0.001                         // (1)
At 1,000,000 eligible requests: 1,000 failures allowed
Observed error ratio: 1% => burn rate = 0.01 / 0.001 = 10  // (2)
🧾 شرح الكود
  1. (1) ده request-based budget مش uptime minutes؛ ماتحوّلش بينهم من غير تعريف SLI.
  2. (2) burn rate عشر مرات المعدل المستدام، مش معناها budget خلصت فوراً؛ المدة وحجم traffic يفرقوا.

اعمل paging لأعراض قابلة للتصرف: فشل مستخدمين، و ، و oldest message age، و burn rate سريع ومستمر. استخدم windows قصيرة وطويلة لتأكيد الفشل وتخفيف الضوضاء. Alert فيها owner و runbook و dashboard و action؛ عالية وحدها غالباً signal للتحقيق أو capacity planning، مش page تلقائية.

Error budget توجه القرار: لو الاستهلاك عالي، قدم reliability work وتقليل مخاطرة deploys باتفاق الفريق، مش قاعدة عمياء لوقف كل تطوير.

#Liveness و readiness و startupLiveness, readiness and startup checks

Liveness بتسأل هل process محتاجة restart، و readiness هل ينفع تستقبل traffic دلوقتي، و startup بتدي وقت للتهيئة قبل تطبيق probes العادية حسب orchestrator. Restart مش هيصلح database خارجية وقعت؛ حط اعتمادها في readiness لو أساسي للخدمة.

using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

builder.Services.AddHealthChecks()
    .AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"])
    .AddCheck<DatabaseReadiness>("database", tags: ["ready"]); // (1)

// After builder.Build():
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = registration => registration.Tags.Contains("live") // (2)
});
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = registration => registration.Tags.Contains("ready")
});

// Application check; IOrderStore is an injected database adapter.
public sealed class DatabaseReadiness(IOrderStore store) : IHealthCheck
{
    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, CancellationToken ct = default)
    {
        return await store.CanConnectAsync(ct)
            ? HealthCheckResult.Healthy()
            : HealthCheckResult.Unhealthy("Database unavailable"); // (3)
    }
}
🧾 شرح الكود
  1. (1) check مخصصة تعتمد على adapter مسجلة في ؛ نفّذ CanConnectAsync بفحص خفيف محدود الوقت. لو رمت exception الـ health framework بيصنفها حسب registration.
  2. (2) self response تثبت إن pipeline قادرة ترد، مش إن كل business behavior سليمة.
  3. (3) readiness تسحب instance من traffic حسب الـ platform، من غير restart تلقائي. امنع عرض تفاصيل dependencies للعامة.

ماتربطش readiness بكل dependency optional؛ ممكن تعمل إخراج جماعي لكل instances بدل degraded service مفيدة. حدد timeouts و probe frequency و failure thresholds عشان ماتعملش حمل مؤذي.

#Production debugging وأدوات .NETProduction debugging and .NET diagnostics

ابدأ بالتأثير، مش اختيار أداة. لو users بتفشل دلوقتي، mitigation آمنة أهم من إكمال التحقيق قبل أي تصرف.

  1. حدد مين متأثر، ونسبة الفشل، والتوقيت، والخدمات الحرجة؛ اختار rollback أو أو عزل dependency حسب الأدلة.
  2. من metrics حدد endpoint و region و version، وقارن deploy أو traffic change.
  3. افتح متأثرة وحدد critical path؛ راجع logs بنفس trace ID من غير أسرار.
  4. اختبر hypothesis واحدة بأدلة مناسبة: profile، أو thread stacks، أو heap retention.
  5. أعد الإنتاج، واعمل regression test، وانشر fix تدريجياً وراقب نفس .
  6. وثّق timeline و contributing factors و actions بمالك وتاريخ؛ post-mortem من غير لوم.
# Tools must be installed; replace 1234 with the target process ID.
dotnet-counters monitor --process-id 1234 --counters System.Runtime
dotnet-trace collect --process-id 1234 --duration 00:00:30
dotnet-dump collect --process-id 1234 --output process.dmp
dotnet-dump analyze process.dmp
الأداةبتختبر إيه
dotnet-countersاتجاه CPU و و و thread pool؛ queue متزايدة مع CPU منخفضة ممكن تشير starvation، مش إثبات لوحدها.
dotnet-traceEventPipe events و profiles حسب providers؛ نافذة محددة تدي stack samples وتوقيت. مش بديل للـ distributed trace.
dotnet-dumpلقطة process لتحليل managed stacks و heap و GC roots؛ مش full native debugger.

حدد collection window و disk budget و impact قبل dump؛ الملف ممكن يحتوي وبيانات شخصية. ارتفاع heap مش دائماً leak؛ افحص retention و GC roots عبر الزمن. Thread count عالي وحده مش سبب كفاية لزيادة ThreadPool minimum.

#Aspire dashboard و دورة التطويرBonusThe Aspire dashboard in the development loop

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

تشغيل و database و محلياً ممكن يخلي تتبع مشكلة بين services متعب. Aspire بيوفر local orchestration و service defaults؛ dashboard بتجمع resource status و logs و و metrics من التطبيقات المتصلة، وبتساعد تربط request بين الخدمات.

  1. شغّل الموارد من AppHost أو وصل dashboard مستقلة حسب بيئتك.
  2. وجّه exporter للعنوان والـ protocol والصلاحيات اللي البيئة وفرتها.
  3. ابدأ request وافتح trace واتنقل للـ logs والـ resource المرتبطة.
  4. جرّب dependency بطيئة أو فاشلة، وشوف timeouts و retry و readiness فعلياً.

Service defaults اختيارات في template، مش سحرية لكل business operation. داشبورد محلية مش بديل تلقائي لتخزين production و retention و alerts. لو عرّضتها على network لازم تحمي الوصول؛ الـ telemetry فيها تفاصيل حساسة.

أسئلة الانترفيو

راجع فهمك

ليه الاختيار ده مناسب؟ إمتى ممكن ماينفعش؟ وإيه اللي هيتغير لو الحمل زاد أو ظهر فشل؟

20.1What are logs, metrics and traces used for?Junior

Logs تفاصيل حدث، و metrics اتجاهات مجمعة، و رحلة request. استخدمهم مع بعض عشان تربط حجم التأثير بمكانه وتفاصيله.

الإجابة النموذجية (English)

I use metrics to understand behavior such as traffic, failure rate and , logs for detailed event context, and to follow a request across components. I connect them with service metadata and trace identity so I can move from a symptom to an affected request and its details. Each has a cost and limitation: metrics lose event detail, logs can become expensive, and sampled traces may not include every request. Together they support investigation rather than automatically proving a root cause.

20.2Why use structured message templates instead of interpolation?Junior

عشان OrderId و Amount يفضلوا fields قابلة للبحث والتجميع، مش نص محتاج parsing. Provider لازم يحافظ على structure.

الإجابة النموذجية (English)

I use stable message templates so values remain named properties rather than disappearing into rendered text. That lets a backend filter by OrderId or by outcome without parsing arbitrary strings. Interpolation also evaluates the string before the logging call, even when that level is disabled. For hot paths I consider source-generated LoggerMessage methods to reduce overhead further. I still check the provider and output format, because structured input does not guarantee every sink stores structured fields.

20.3What does LoggerMessage source generation provide?Mid

Partial methods متولدة وقت compile، بأسماء fields و types ثابتة و overhead أقل. مش backend ولا بديل لسياسة log levels و redaction.

الإجابة النموذجية (English)

I use LoggerMessage attributes on partial methods in partial types to generate strongly typed logging implementations at compile time. This reduces repeated template processing and compared with common extension-method calls, and diagnostics catch signature mistakes. It is useful for frequent events with stable schemas. It does not replace ILogger providers, retention policies or privacy controls. I still choose meaningful levels and event IDs, avoid expensive arguments when disabled, and ensure the configured sink preserves the properties I need.

20.4How do you choose log levels?Junior

حسب أثر الحدث: expected milestones Information، و degradation Warning، و فشل عملية Error، و خطر شامل Critical. Validation مش Error تلقائياً.

الإجابة النموذجية (English)

I choose levels according to operational meaning. Information records useful expected milestones, Warning records recoverable degradation, Error records failed operations requiring investigation, and Critical indicates a severe threat to service continuity or integrity. Debug and provide temporary diagnostic detail with controlled volume. I do not turn every rejected input into an error or log the same exception at every layer. The team agrees on these meanings so dashboards and alerts reflect impact rather than inconsistent developer preferences.

20.5How do trace IDs, span IDs and correlation IDs differ?Mid

ID للرحلة، و ID للخطوة، و correlation ID ممكن business workflow أطول. Traceparent بينقل context مش authorization.

الإجابة النموذجية (English)

I use a ID to identify a distributed execution and a ID to identify one operation inside it. W3C traceparent carries trace context so downstream services can continue the relationship. A business correlation ID can connect a longer workflow, including retries or separate traces, and therefore need not equal the trace ID. I propagate context through and explicitly through messaging integrations. I validate external correlation fields and never treat them as authentication or permission evidence.

20.6What does OpenTelemetry do in a .NET application?Mid

Standard و و exporters. ActivitySource و Meter من ، و نقل. Dashboard و storage بييجوا من backend.

الإجابة النموذجية (English)

I use OpenTelemetry to collect and export telemetry through standard and configurable pipelines. In , ActivitySource and Activity represent , while Meter produces measurements. I register the relevant sources and meters, configure and resources, and export through to a collector or backend. Logs have their own pipeline. OpenTelemetry is not itself a storage database or dashboard, and changing backends can still require configuration and semantic adjustments even when application instrumentation stays the same.

20.7Why can ActivitySource.StartActivity return null?Mid

مفيش listener مهتم أو مش محتاج Activity. استخدم ?. وماتعملش شغل غالي عشان tags لو مش هتتجمع.

الإجابة النموذجية (English)

I expect StartActivity to return null when no interested listener exists or the decision does not require an Activity. That keeps unobserved inexpensive. I use nullable access for tags and status, and register the ActivitySource name in the OpenTelemetry tracing configuration when I want it collected. I also avoid constructing expensive diagnostic payloads unnecessarily. Instrumentation should preserve business behavior whether a listener is present, tracing is sampled or the exporter is temporarily unavailable.

20.8What are RED and USE metrics?Mid

للخدمات Rate و Errors و Duration، و للموارد Utilization و Saturation و Errors. الاتنين يربطوا تجربة المستخدم بسبب resource محتمل.

الإجابة النموذجية (English)

I use to describe a service through request rate, errors and duration, and to inspect resources through utilization, saturation and errors. RED tells me whether users are experiencing a problem; USE helps investigate whether , memory, disk or connection capacity contributes. I distinguish busy resources from queued demand, because high utilization alone is not always harmful. I correlate these measurements with deployments and instead of assuming one high resource value proves the cause.

20.9Why use histograms for latency, and can you average p95 values?Mid

توزيع مش قيمة واحدة؛ percentiles تبين tail. مينفعش average لـ instances؛ اجمع distributions المتوافقة الأول.

الإجابة النموذجية (English)

I use because is a distribution and an average can hide a small group of very slow requests. A backend estimates percentiles from the observations or buckets, so bucket boundaries and the measurement window matter. I do not average values from different instances because that does not produce the overall p95. I compatible distributions first. For a fixed latency objective, I also measure the fraction of eligible requests below the threshold directly.

20.10What is metric cardinality and why does it matter?Senior

عدد التركيبات المختلفة للـ labels؛ OrderId و email بيزودوا series بلا حد. استعمل operation و outcome محدودين و خزن التفاصيل في logs أو .

الإجابة النموذجية (English)

I treat as the number of distinct label combinations producing time series. Adding user IDs or order IDs can grow that count with every request, increasing memory, storage and query costs. I use bounded dimensions such as operation and outcome for metrics, and move individual identifiers to protected logs or where appropriate. I also review combinations of seemingly small dimensions, because their product can still become large, and monitor dropped measurements and backend limits.

20.11Explain SLIs, SLOs and error budgets.Senior

قياس معرف، و هدف خلال نافذة، و budget نسبة الفشل المسموحة. Request-based budget مش نفس downtime minutes، و burn rate يقيس سرعة الاستهلاك.

الإجابة النموذجية (English)

I define an as a measurement of service experience and an as its target over a specified window. The error budget is the allowed shortfall, such as the permitted fraction of failed eligible requests. I define eligibility, business success and the data source before calculating it. Burn rate compares observed failures with the sustainable budget rate. The budget then guides reliability priorities and deployment risk under an agreed policy, rather than becoming a number disconnected from user experience.

20.12What should trigger an on-call alert?Senior

أعراض user impact قابلة للتصرف، و burn rate و backlog age. كل alert ليها owner و runbook؛ high لوحدها مش دايماً page.

الإجابة النموذجية (English)

I page for actionable user-impacting symptoms or rapid sustained budget consumption, rather than every unusual infrastructure value. Examples include checkout failures, excessive and a growing age of unprocessed payment events. I use suitable windows and thresholds to avoid flapping and low-volume noise. Every page has an owner, a runbook and a useful next action. Resource signals such as high remain valuable for diagnosis and capacity planning even when they do not justify waking someone immediately.

20.13How do liveness and readiness differ?Mid

Liveness قرار restart للعملية، و readiness قرار توجيه traffic. Database down مش سبب restart لكل ؛ افصل check tags وحدد dependencies الأساسية فقط.

الإجابة النموذجية (English)

I use liveness to indicate whether restarting the process is appropriate and readiness to indicate whether it should receive traffic. A database outage can make a service unready without making the process itself unhealthy for liveness. Putting shared dependencies in liveness can create restart storms without repairing the dependency. I keep checks cheap and bounded, include only essential readiness dependencies, and let startup probing accommodate initialization when supported by the platform. Detailed health output is restricted rather than exposed publicly.

20.14How do you investigate a production performance incident?Senior

Impact و mitigation، بعدين metrics و و logs، واختبار hypothesis بأداة مناسبة، و fix بـ regression و rollout ومراجعة أسباب من غير لوم.

الإجابة النموذجية (English)

I establish the affected users, timing and severity, then mitigate safely through rollback or when needed. Metrics narrow the endpoint, version and resource pattern; show the critical path, and correlated logs add details. I choose diagnostics based on a hypothesis: counters for trends, a bounded trace for sampled execution, or a dump for retained objects and stacks. I reproduce the issue, add a regression test, roll out gradually and document contributing factors with owned follow-up actions.

20.15How does the Aspire dashboard help, and what are its limits?Mid

بتجمع resource status و logs و و metrics محلياً عبر التكامل. مش بديل تلقائي لتخزين طويل و production alerts، ولازم تحمي الوصول.

الإجابة النموذجية (English)

I use the Aspire dashboard to inspect connected resources and navigate between logs, metrics and distributed during development. Service defaults and local orchestration make it easier to reproduce dependency failures and verify propagation. I still instrument meaningful business operations and configure exporters correctly. The dashboard does not automatically provide a production retention and alerting strategy, and standalone use needs deliberate connectivity and authentication. I protect access because telemetry can expose operational details and sensitive application context.

اختبر نفسك

إجابات الاختبار وعلامات إكمال المحاور بتتحفظ على المتصفح ده، ومش بتتنقل لأجهزة تانية.

النتيجة: 0 / 0

Which signal follows one request through API, database and payment service?

بتحدد خطوات الرحلة ومددها وعلاقاتها.

Why prefer a stable message template in logging?

الـ fields تفضل قابلة للبحث بدل parsing نص حر.

What should you do when StartActivity returns null?

ده سلوك طبيعي لما مفيش listener أو مش محتاج Activity.

Which label is generally suitable for a request-count metric?

القيم المحدودة بتمنع تضخم time series.

How should you compute a service-wide p95 across instances?

Percentiles مش قابلة للتجميع بالمتوسط.

A 99.9% request-success SLO permits how many failures per million eligible requests?

النسبة المسموحة 0.1% من مليون.

The database is unavailable but the API process responds normally. Which is appropriate?

Restart مش هيصلح dependency خارجية؛ readiness تتحكم في traffic.

What is OTLP?

النقل مختلف عن التخزين والعرض.

Which tool is suited to inspecting a managed heap snapshot and GC roots?

Dump بتوفر لقطة لتحليل heap و stacks؛ راعي الأثر والبيانات الحساسة.

What makes an on-call page useful?

الضوضاء من غير action بتعمل alert fatigue.