שימוש במדדים בצד הלקוח כדי לפתור בעיות שקשורות לזמן אחזור גבוה

ב-Memorystore for Redis יש מדדים בזמן אמת בצד השרת למעקב אחרי קצב העברת הנתונים, ניצול המעבד (CPU) והשימוש בזיכרון, אבל יכול להיות שהנתונים האלה לבדם לא יסבירו למה יש זמן אחזור ארוך באפליקציית הלקוח במערכות מבוזרות מורכבות.

מדדים בצד הלקוח פותרים את הבעיה הזו על ידי מתן שקיפות למחזור המלא של הבקשה והתגובה. הם מודדים פקודה מהרגע שהאפליקציה יוזמת אותה ועד שהיא מעבדת את התגובה. בעזרת תיעוד נקודות הנתונים האלה, תוכלו לקבוע במדויק אם מקור זמן האחזור הוא בלוגיקה של האפליקציה, בנתיב הרשת או בשרת Redis.

לפני שמתחילים

מוודאים שאפליקציית הלקוח משתמשת בחשבון שירות, ושהוקצו לה תפקידי ניהול הזהויות והרשאות הגישה (IAM) הבאים:

  • ‫roles/cloudtrace.agent (סוכן Cloud Trace)
  • roles/monitoring.metricWriter (כתיבת מדדי מעקב)

מידע נוסף על הקצאת תפקידים מופיע במדריך למתחילים בנושא הקצאת תפקיד ב-IAM באמצעות מסוף Google Cloud .

הפעלת Cloud Monitoring API

כדי לייצא מדדים בצד הלקוח אל Monitoring, צריך להפעיל את Monitoring API באפליקציה. ייצוא והצגה חזותית של המדדים האלה ב-Monitoring מאפשרים לכם לזהות את שורש הבעיה של צווארי הבקבוק, כדי לקבוע מה המקור של זמן האחזור.

כדי להפעיל את Monitoring API:

  1. במסוף Google Cloud , נכנסים לדף APIs & Services.

    לדף "ממשקי API ושירותים"

  2. בוחרים את הפרויקט שבו יצרתם את המכונה של Memorystore for Redis.

  3. לוחצים על Enable APIs and services.

  4. חיפוש של monitoring.

  5. בתוצאות החיפוש, לוחצים על Cloud Monitoring API.

  6. אם מופיע הכיתוב API enabled, סימן שה-API כבר מופעל. אם לא, לוחצים על Enable.

הפעלת Cloud Trace API

כדי להציג מעקבים מבוזרים ב-Trace, צריך להפעיל את Trace API. לאחר מכן תוכלו להשתמש ב-Trace Explorer כדי להציג את המעקבים האלה, לאבחן צווארי בקבוק ולבודד את מקור זמן האחזור באפליקציה.

כדי להפעיל את Trace API:

  1. במסוף Google Cloud , נכנסים לדף APIs & Services.

    לדף "ממשקי API ושירותים"

  2. בוחרים את הפרויקט שבו יצרתם את המכונה של Memorystore for Redis.

  3. לוחצים על Enable APIs and services.

  4. חיפוש של trace.

  5. בתוצאות החיפוש, לוחצים על Cloud Trace API.

  6. אם מופיע הכיתוב API enabled, סימן שה-API כבר מופעל. אם לא, לוחצים על Enable.

הפעלת Telemetry API

כדי לייצא מדדים בצד הלקוח באמצעות פרוטוקול OpenTelemetry‏ (OTLP), צריך להפעיל את Telemetry API. אחר כך תוכלו להשתמש בייצוא סטנדרטי של OTLP בקוד הלקוח, במקום בייצוא של Google Cloud ספציפי לספק.

מייצאים רגילים של OTLP מונעים אובדן נתונים. הם גם מפשטים את יחסי התלות ומבטיחים שהנתונים יישארו ניידים בין פלטפורמות אחרות של ניראות. אחרי שכותבים את קוד הטלמטריה פעם אחת, אפשר להעביר את הנתונים לכל אחת מהפלטפורמות האלה על ידי עדכון ההגדרות. לא צריך לשכתב את הקוד עם קבוצה חדשה של ספריות קנייניות לכל פלטפורמה.

כדי להפעיל את Telemetry API:

  1. במסוף Google Cloud , נכנסים לדף APIs & Services.

    לדף "ממשקי API ושירותים"

  2. בוחרים את הפרויקט שבו יצרתם את המכונה של Memorystore for Redis.

  3. לוחצים על Enable APIs and services.

  4. חיפוש של telemetry.

  5. בתוצאות החיפוש, לוחצים על Telemetry API.

  6. אם מופיע הכיתוב API enabled, סימן שה-API כבר מופעל. אם לא, לוחצים על Enable.

הפעלת מדדים בצד הלקוח

כדי להפעיל מדדים בצד הלקוח, צריך להוסיף לקוד של האפליקציה את ה-SDK של OpenTelemetry ואת כלי הייצוא של OpenTelemetry OTLP, שמטרגטים את Telemetry API. הכלים של OpenTelemetry, שפועלים ישירות בתוך ספריית הלקוח של Redis באפליקציה, מתעדים את המדדים. כך האפליקציה יכולה לתעד נקודות על הגרף של זמן אחזור ולייצא אותן ל-Monitoring ול-Trace לצורך הצגה חזותית.

כדי להפעיל מדדים בצד הלקוח, אפשר להשתמש ב-Go, ב-Java, ב-Node.js או ב-Python. בכרטיסיות הבאות מופיע מידע על הפעלת המדדים לכל שפה.

המשך

  1. כדי להתקין את יחסי התלות הנדרשים של OpenTelemetry ושל כלי הייצוא של OTLP, מריצים את הפקודות הבאות בטרמינל:

      go get github.com/gomodule/redigo/redis@latest
      go get go.opentelemetry.io/otel
      go get go.opentelemetry.io/otel/sdk
      go get go.opentelemetry.io/otel/sdk/metric
      go get go.opentelemetry.io/contrib/detectors/gcp
      go get go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc
      go get go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc
      go get golang.org/x/oauth2/google
      go get google.golang.org/grpc
  2. כדי להפעיל את המדדים בצד הלקוח, יוצרים קובץ main.go ומוסיפים לו את הקוד הבא:

    package main
    
    import (
    	"context"
    	"fmt"
    	"log"
    	"os"
    	"time"
    
    	"github.com/gomodule/redigo/redis"
    	"go.opentelemetry.io/contrib/detectors/gcp"
    	"go.opentelemetry.io/otel"
    	"go.opentelemetry.io/otel/attribute"
    	"go.opentelemetry.io/otel/codes"
    	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
    	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
    	"go.opentelemetry.io/otel/metric"
    	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
    	"go.opentelemetry.io/otel/sdk/resource"
    	sdktrace "go.opentelemetry.io/otel/sdk/trace"
    	"go.opentelemetry.io/otel/trace"
    	"golang.org/x/oauth2/google"
    	"google.golang.org/grpc"
    	"google.golang.org/grpc/credentials/oauth"
    )
    
    // MetricClient encapsulates the tracer and metric histograms to avoid package-level globals.
    type MetricClient struct {
    	tracer           trace.Tracer
    	rttHist          metric.Float64Histogram
    	clientBlockHist  metric.Float64Histogram
    	appBlockHist     metric.Float64Histogram
    	retryCounter     metric.Int64Counter
    	connErrorCounter metric.Int64Counter
    }
    
    // sleep hook enables lightning-fast unit tests by stubbing out real time.Sleep
    var sleep = time.Sleep
    
    // sinceMs calculates elapsed time in fractional milliseconds to avoid truncating sub-millisecond durations.
    func sinceMs(start time.Time) float64 {
    	return float64(time.Since(start).Microseconds()) / 1000.0
    }
    
    func initTelemetry(ctx context.Context) (*MetricClient, func(), error) {
    	creds, err := google.FindDefaultCredentials(ctx, "https://www.googleapis.com/auth/cloud-platform")
    	if err != nil {
    		return nil, nil, fmt.Errorf("google.FindDefaultCredentials: %w", err)
    	}
    	perRPCCreds := oauth.TokenSource{TokenSource: creds.TokenSource}
    
    	res, err := resource.New(
    		ctx,
    		resource.WithDetectors(gcp.NewDetector()),
    		resource.WithFromEnv(),
    		resource.WithAttributes(attribute.String("gcp.project_id", creds.ProjectID)),
    	)
    	if err != nil {
    		return nil, nil, fmt.Errorf("resource.New: %w", err)
    	}
    
    	traceExporter, err := otlptracegrpc.New(
    		ctx,
    		otlptracegrpc.WithEndpoint("telemetry.googleapis.com:443"),
    		otlptracegrpc.WithDialOption(grpc.WithPerRPCCredentials(perRPCCreds)),
    		otlptracegrpc.WithCompressor("gzip"),
    	)
    	if err != nil {
    		return nil, nil, fmt.Errorf("otlptracegrpc.New: %w", err)
    	}
    	tp := sdktrace.NewTracerProvider(
    		sdktrace.WithBatcher(traceExporter),
    		sdktrace.WithResource(res),
    	)
    	otel.SetTracerProvider(tp)
    	tracer := tp.Tracer("redigo.client")
    
    	metricExporter, err := otlpmetricgrpc.New(
    		ctx,
    		otlpmetricgrpc.WithEndpoint("telemetry.googleapis.com:443"),
    		otlpmetricgrpc.WithDialOption(grpc.WithPerRPCCredentials(perRPCCreds)),
    		otlpmetricgrpc.WithCompressor("gzip"),
    	)
    	if err != nil {
    		_ = tp.Shutdown(ctx)
    		return nil, nil, fmt.Errorf("otlpmetricgrpc.New: %w", err)
    	}
    	mp := sdkmetric.NewMeterProvider(
    		sdkmetric.WithResource(res),
    		sdkmetric.WithReader(sdkmetric.NewPeriodicReader(
    			metricExporter,
    			sdkmetric.WithInterval(10*time.Second),
    		)),
    	)
    	otel.SetMeterProvider(mp)
    	meter := mp.Meter("redigo.metrics")
    
    	rttHist, err := meter.Float64Histogram("redis_client_rtt", metric.WithUnit("ms"))
    	if err != nil {
    		return nil, nil, fmt.Errorf("redis_client_rtt histogram: %w", err)
    	}
    	clientBlockHist, err := meter.Float64Histogram("redis_client_blocking_latency", metric.WithUnit("ms"))
    	if err != nil {
    		return nil, nil, fmt.Errorf("redis_client_blocking_latency histogram: %w", err)
    	}
    	appBlockHist, err := meter.Float64Histogram("redis_application_blocking_latency", metric.WithUnit("ms"))
    	if err != nil {
    		return nil, nil, fmt.Errorf("redis_application_blocking_latency histogram: %w", err)
    	}
    	retryCounter, err := meter.Int64Counter("redis_retry_count")
    	if err != nil {
    		return nil, nil, fmt.Errorf("redis_retry_count counter: %w", err)
    	}
    	connErrorCounter, err := meter.Int64Counter("redis_connectivity_error_count")
    	if err != nil {
    		return nil, nil, fmt.Errorf("redis_connectivity_error_count counter: %w", err)
    	}
    
    	client := &MetricClient{
    		tracer:           tracer,
    		rttHist:          rttHist,
    		clientBlockHist:  clientBlockHist,
    		appBlockHist:     appBlockHist,
    		retryCounter:     retryCounter,
    		connErrorCounter: connErrorCounter,
    	}
    
    	initAttrs := metric.WithAttributes(attribute.String("operation", "startup"))
    	client.retryCounter.Add(ctx, 0, initAttrs)
    	client.connErrorCounter.Add(ctx, 0, initAttrs)
    
    	shutdown := func() {
    		shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    		defer cancel()
    		if err := tp.Shutdown(shutdownCtx); err != nil {
    			log.Printf("Error shutting down tracer provider: %v", err)
    		}
    		if err := mp.Shutdown(shutdownCtx); err != nil {
    			log.Printf("Error shutting down meter provider: %v", err)
    		}
    	}
    
    	return client, shutdown, nil
    }
    
    func (c *MetricClient) smartRedisCall(ctx context.Context, pool *redis.Pool, operationName string, commandName string, args ...interface{}) (interface{}, error) {
    	// Create a dedicated child span for the Redis command
    	ctx, span := c.tracer.Start(ctx, operationName)
    	span.SetAttributes(attribute.String("redis.command", commandName))
    	defer span.End()
    
    	maxRetries := 3
    	attempt := 0
    	metricOpts := metric.WithAttributes(attribute.String("operation", operationName))
    	var lastErr error
    
    	for attempt < maxRetries {
    		poolStart := time.Now()
    		// Use GetContext to respect context deadlines and cancellation
    		conn, err := pool.GetContext(ctx)
    		c.clientBlockHist.Record(ctx, sinceMs(poolStart), metricOpts)
    
    		if err != nil {
    			c.connErrorCounter.Add(ctx, 1, metricOpts)
    			c.retryCounter.Add(ctx, 1, metricOpts)
    			span.RecordError(err)
    			span.SetStatus(codes.Error, err.Error())
    			lastErr = err
    			attempt++
    			if attempt >= maxRetries {
    				break
    			}
    			sleep(time.Duration(100<<attempt) * time.Millisecond)
    			continue
    		}
    
    		// Check if the connection is dead
    		if err := conn.Err(); err != nil {
    			conn.Close()
    			c.connErrorCounter.Add(ctx, 1, metricOpts)
    			c.retryCounter.Add(ctx, 1, metricOpts)
    			span.RecordError(err)
    			span.SetStatus(codes.Error, err.Error())
    			lastErr = err
    			attempt++
    			if attempt >= maxRetries {
    				break
    			}
    			sleep(time.Duration(100<<attempt) * time.Millisecond)
    			continue
    		}
    
    		reqStart := time.Now()
    		// Redigo has no native DoContext; pass timeouts using redis.DoWithTimeout when context has a deadline
    		var reply interface{}
    		if deadline, ok := ctx.Deadline(); ok {
    			reply, err = redis.DoWithTimeout(conn, time.Until(deadline), commandName, args...)
    		} else {
    			reply, err = conn.Do(commandName, args...)
    		}
    		c.rttHist.Record(ctx, sinceMs(reqStart), metricOpts)
    		conn.Close()
    
    		if err != nil {
    			c.retryCounter.Add(ctx, 1, metricOpts)
    			span.RecordError(err)
    			span.SetStatus(codes.Error, err.Error())
    			lastErr = err
    			attempt++
    			if attempt >= maxRetries {
    				break
    			}
    			sleep(time.Duration(100<<attempt) * time.Millisecond)
    			continue
    		}
    
    		appStart := time.Now()
    		// Replace fmt.Sprintf to remove unnecessary string formatting overhead
    		sleep(2 * time.Millisecond)
    		c.appBlockHist.Record(ctx, sinceMs(appStart), metricOpts)
    
    		// Reset span status to Ok if the retry or execution eventually succeeds
    		span.SetStatus(codes.Ok, "")
    
    		return reply, nil
    	}
    	return nil, fmt.Errorf("max retries reached for %s: %w", operationName, lastErr)
    }
    
    func main() {
    	ctx := context.Background()
    	client, shutdown, err := initTelemetry(ctx)
    	if err != nil {
    		log.Printf("Failed to initialize telemetry: %v", err)
    		os.Exit(1)
    	}
    	defer shutdown()
    
    	redisHost := os.Getenv("REDISHOST")
    	redisPort := os.Getenv("REDISPORT")
    	if redisPort == "" {
    		redisPort = "6379"
    	}
    
    	pool := &redis.Pool{
    		MaxIdle:     10,
    		MaxActive:   20,
    		IdleTimeout: 240 * time.Second,
    		Wait:        true,
    		Dial: func() (redis.Conn, error) {
    			return redis.Dial("tcp", fmt.Sprintf("%s:%s", redisHost, redisPort))
    		},
    	}
    	defer pool.Close()
    
    	ctx, span := client.tracer.Start(ctx, "fetch_data_span")
    	defer span.End()
    
    	// Simple write and read operations
    	_, err = client.smartRedisCall(ctx, pool, "set_user", "SET", "user:123", "active")
    	if err != nil {
    		log.Printf("Error setting data: %v", err)
    	}
    
    	val, err := client.smartRedisCall(ctx, pool, "get_user", "GET", "user:123")
    	if err != nil {
    		log.Printf("Error fetching data: %v", err)
    	} else {
    		log.Printf("Retrieved value: %s", val)
    	}
    }
    
  3. מריצים את האפליקציה למשך דקה לפחות כדי לתת למייצא מספיק זמן לאסוף את המדדים שפורסמו ולשלוח אותם ל-Monitoring.

Java

  1. כדי להתקין את יחסי התלות הנדרשים של OpenTelemetry ושל מייצא OTLP, מוסיפים את הקוד הבא לקובץ pom.xml של האפליקציה:

    <dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>5.1.0</version>
        </dependency>
        <dependency>
            <groupId>io.opentelemetry</groupId>
            <artifactId>opentelemetry-api</artifactId>
            <version>1.44.1</version>
        </dependency>
        <dependency>
            <groupId>io.opentelemetry</groupId>
            <artifactId>opentelemetry-sdk</artifactId>
            <version>1.44.1</version>
        </dependency>
        <dependency>
            <groupId>io.opentelemetry</groupId>
            <artifactId>opentelemetry-exporter-otlp</artifactId>
            <version>1.44.1</version>
        </dependency>
        <dependency>
            <groupId>io.opentelemetry</groupId>
            <artifactId>opentelemetry-sdk-extension-autoconfigure-spi</artifactId>
            <version>1.44.1</version>
        </dependency>
        <dependency>
            <groupId>io.opentelemetry.contrib</groupId>
            <artifactId>opentelemetry-gcp-resources</artifactId>
            <version>1.37.0-alpha</version>
        </dependency>
        <dependency>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
            <version>1.24.0</version>
        </dependency>
    
        <!-- Testing Dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>4.11.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.36</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  2. כדי להפעיל את המדדים בצד הלקוח, יוצרים קובץ RedisTelemetryApp.java ומוסיפים לו את הקוד הבא:

    import com.google.auth.oauth2.GoogleCredentials;
    import io.opentelemetry.api.OpenTelemetry;
    import io.opentelemetry.api.common.AttributeKey;
    import io.opentelemetry.api.common.Attributes;
    import io.opentelemetry.api.metrics.DoubleHistogram;
    import io.opentelemetry.api.metrics.LongCounter;
    import io.opentelemetry.api.metrics.Meter;
    import io.opentelemetry.api.trace.Span;
    import io.opentelemetry.api.trace.Tracer;
    import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter;
    import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
    import io.opentelemetry.sdk.OpenTelemetrySdk;
    import io.opentelemetry.sdk.metrics.SdkMeterProvider;
    import io.opentelemetry.sdk.metrics.export.MetricExporter;
    import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader;
    import io.opentelemetry.sdk.resources.Resource;
    import io.opentelemetry.sdk.trace.SdkTracerProvider;
    import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
    import io.opentelemetry.sdk.trace.export.SpanExporter;
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    import redis.clients.jedis.exceptions.JedisConnectionException;
    
    import java.io.IOException;
    import java.time.Duration;
    import java.util.Collections;
    import java.util.Map;
    import java.util.function.Function;
    import java.util.function.Supplier;
    
    /**
     * Sample application demonstrating client-side metrics and tracing for
     * Google Cloud Memorystore for Redis using OpenTelemetry OTLP exporters.
     */
    public final class RedisTelemetryApp {
        /** Attribute key for Redis operation names. */
        private static final AttributeKey<String> ATTR_OPERATION =
                AttributeKey.stringKey("operation");
    
        /** Attribute key for the detected cloud account/project ID. */
        private static final AttributeKey<String> ATTR_CLOUD_ACCOUNT_ID =
                AttributeKey.stringKey("cloud.account.id");
    
        /** Attribute key required by the Google Cloud Telemetry API. */
        private static final AttributeKey<String> ATTR_GCP_PROJECT_ID =
                AttributeKey.stringKey("gcp.project_id");
    
        /** Google Cloud Telemetry API OTLP endpoint. */
        private static final String TELEMETRY_ENDPOINT =
                "https://telemetry.googleapis.com:443";
    
        /** OAuth2 scope for Google Cloud APIs. */
        private static final String CLOUD_PLATFORM_SCOPE =
                "https://www.googleapis.com/auth/cloud-platform";
    
        /** HTTP/gRPC Authorization header name. */
        private static final String AUTHORIZATION_HEADER = "Authorization";
    
        /** Prefix for OAuth2 Bearer tokens. */
        private static final String BEARER_PREFIX = "Bearer ";
    
        /** Maximum number of Redis reconnection attempts. */
        private static final int MAX_RETRIES = 3;
    
        /** Maximum total connections for the Jedis pool. */
        private static final int POOL_MAX_TOTAL = 20;
    
        /** Interval in seconds for exporting metrics to Google Cloud. */
        private static final long METRIC_INTERVAL_SECONDS = 10L;
    
        /** Base multiplier for exponential backoff sleep (in milliseconds). */
        private static final long RETRY_BACKOFF_BASE_MS = 100L;
    
        /** Conversion factor from Nanoseconds to Milliseconds. */
        private static final double NANO_TO_MS = 1_000_000.0;
    
        /** Default Redis port. */
        private static final int DEFAULT_REDIS_PORT = 6379;
    
        /** OpenTelemetry SDK instance used for flushing telemetry on shutdown. */
        private static OpenTelemetrySdk openTelemetrySdk;
    
        /** OpenTelemetry Tracer instance for recording trace spans. */
        private static Tracer tracer;
    
        /** OpenTelemetry Histogram for Redis round-trip time. */
        private static DoubleHistogram rttHist;
    
        /** OpenTelemetry Histogram for pool blocking latency. */
        private static DoubleHistogram clientBlockHist;
    
        /** OpenTelemetry Histogram for application logic blocking latency. */
        private static DoubleHistogram appBlockHist;
    
        /** OpenTelemetry Counter for Redis reconnection retry events. */
        private static LongCounter retryCounter;
    
        /** OpenTelemetry Counter for Redis connectivity errors. */
        private static LongCounter connErrorCounter;
    
        /** Shared Jedis connection pool. */
        private static JedisPool jedisPool;
    
        /**
         * Private constructor to prevent instantiation of this utility class.
         */
        private RedisTelemetryApp() {
        }
    
        /**
         * Main entry point for running the sample application.
         *
         * @param args Command line arguments (not used).
         * @throws IOException If Google Cloud credentials cannot be loaded.
         */
        public static void main(final String[] args) throws IOException {
            setupTelemetry();
    
            final String host = System.getenv()
                    .getOrDefault("REDISHOST", "localhost");
            final int port = Integer.parseInt(System.getenv()
                    .getOrDefault("REDISPORT",
                            String.valueOf(DEFAULT_REDIS_PORT)));
    
            final JedisPoolConfig poolConfig = new JedisPoolConfig();
            poolConfig.setMaxTotal(POOL_MAX_TOTAL);
            poolConfig.setBlockWhenExhausted(true);
            jedisPool = new JedisPool(poolConfig, host, port);
    
            try {
                run();
            } finally {
                if (jedisPool != null) {
                    jedisPool.close();
                }
                if (openTelemetrySdk != null) {
                    openTelemetrySdk.close();
                }
            }
        }
    
        /**
         * Executes the core business logic of reading and writing to Redis.
         *
         * @return The string retrieved from the Redis 'get' operation.
         */
        static String run() {
            final Span span = tracer.spanBuilder("process_user_span")
                    .startSpan();
            try {
                smartRedisCall("set_user", jedis ->
                        jedis.set("user:123", "active"));
    
                final String result = smartRedisCall("get_user", jedis ->
                        jedis.get("user:123"));
                System.out.println("Retrieved: " + result);
                return result;
            } catch (Exception e) {
                span.recordException(e);
                throw e;
            } finally {
                span.end();
            }
        }
    
        /**
         * Injects mocked or no-op telemetry and pool instances for unit testing.
         *
         * @param pool              The mocked or test JedisPool instance.
         * @param testOpenTelemetry The OpenTelemetry instance to use for testing.
         */
        static void initForTest(
                final JedisPool pool,
                final OpenTelemetry testOpenTelemetry) {
            jedisPool = pool;
            tracer = testOpenTelemetry.getTracer("jedis.client");
            final Meter meter = testOpenTelemetry.getMeter("jedis.metrics");
    
            rttHist = meter.histogramBuilder("redis_client_rtt")
                    .setUnit("ms").build();
            clientBlockHist = meter
                    .histogramBuilder("redis_client_blocking_latency")
                    .setUnit("ms").build();
            appBlockHist = meter
                    .histogramBuilder("redis_application_blocking_latency")
                    .setUnit("ms").build();
            retryCounter = meter.counterBuilder("redis_retry_count").build();
            connErrorCounter = meter
                    .counterBuilder("redis_connectivity_error_count")
                    .build();
    
            retryCounter.add(0, Attributes.of(ATTR_OPERATION, "startup"));
            connErrorCounter.add(0, Attributes.of(ATTR_OPERATION, "startup"));
        }
    
        /**
         * Configures the production OpenTelemetry SDK to export Traces and Metrics
         * via OTLP to Google Cloud.
         *
         * @throws IOException If Google Application Default Credentials fail.
         */
        private static void setupTelemetry() throws IOException {
            final GoogleCredentials credentials = GoogleCredentials
                    .getApplicationDefault()
                    .createScoped(Collections.singletonList(CLOUD_PLATFORM_SCOPE));
            credentials.refreshIfExpired();
    
            final Supplier<Map<String, String>> headerSupplier = () -> {
                try {
                    synchronized (credentials) {
                        credentials.refreshIfExpired();
                        return Collections.singletonMap(
                                AUTHORIZATION_HEADER,
                                BEARER_PREFIX
                                        + credentials.getAccessToken()
                                                .getTokenValue());
                    }
                } catch (IOException e) {
                    throw new RuntimeException(
                            "Failed to refresh Google credentials", e);
                }
            };
    
            final Resource defaultResource = Resource.getDefault();
            String projectId =
                    defaultResource.getAttributes().get(ATTR_CLOUD_ACCOUNT_ID);
            if (projectId == null || projectId.isEmpty()) {
                projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
            }
            final Resource resource = projectId != null && !projectId.isEmpty()
                    ? defaultResource.merge(Resource.create(
                            Attributes.of(ATTR_GCP_PROJECT_ID, projectId)))
                    : defaultResource;
    
            final SpanExporter traceExporter = OtlpGrpcSpanExporter.builder()
                    .setEndpoint(TELEMETRY_ENDPOINT)
                    .setHeaders(headerSupplier)
                    .build();
            final SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
                    .setResource(resource)
                    .addSpanProcessor(
                            BatchSpanProcessor.builder(traceExporter).build())
                    .build();
    
            final MetricExporter metricExporter = OtlpGrpcMetricExporter.builder()
                    .setEndpoint(TELEMETRY_ENDPOINT)
                    .setHeaders(headerSupplier)
                    .build();
            final SdkMeterProvider meterProvider = SdkMeterProvider.builder()
                    .setResource(resource)
                    .registerMetricReader(
                            PeriodicMetricReader.builder(metricExporter)
                                    .setInterval(Duration.ofSeconds(
                                            METRIC_INTERVAL_SECONDS))
                                    .build())
                    .build();
    
            openTelemetrySdk = OpenTelemetrySdk.builder()
                    .setTracerProvider(tracerProvider)
                    .setMeterProvider(meterProvider)
                    .buildAndRegisterGlobal();
    
            tracer = openTelemetrySdk.getTracer("jedis.client");
            final Meter meter = openTelemetrySdk.getMeter("jedis.metrics");
    
            rttHist = meter.histogramBuilder("redis_client_rtt")
                    .setUnit("ms").build();
            clientBlockHist = meter
                    .histogramBuilder("redis_client_blocking_latency")
                    .setUnit("ms").build();
            appBlockHist = meter
                    .histogramBuilder("redis_application_blocking_latency")
                    .setUnit("ms").build();
            retryCounter = meter.counterBuilder("redis_retry_count").build();
            connErrorCounter = meter
                    .counterBuilder("redis_connectivity_error_count")
                    .build();
    
            retryCounter.add(0, Attributes.of(ATTR_OPERATION, "startup"));
            connErrorCounter.add(0, Attributes.of(ATTR_OPERATION, "startup"));
        }
    
        /**
         * Wraps a Redis operation with latency metrics, reconnection retry logic,
         * and trace spans.
         *
         * @param <T>           The return type of the Redis operation.
         * @param operationName The name of the operation for metric attributes.
         * @param operation     The Redis command lambda to execute safely.
         * @return The return value from the Redis command.
         */
        private static <T> T smartRedisCall(
                final String operationName,
                final Function<Jedis, T> operation) {
            int attempt = 0;
            final Attributes attrs = Attributes.of(ATTR_OPERATION,
                    operationName);
    
            final Span span = tracer.spanBuilder(operationName).startSpan();
    
            try {
                while (attempt < MAX_RETRIES) {
                    final long poolStart = System.nanoTime();
                    try (Jedis jedis = jedisPool.getResource()) {
                        clientBlockHist.record((System.nanoTime() - poolStart)
                                / NANO_TO_MS, attrs);
    
                        final long reqStart = System.nanoTime();
                        final T response = operation.apply(jedis);
                        rttHist.record((System.nanoTime() - reqStart)
                                / NANO_TO_MS, attrs);
    
                        final long appStart = System.nanoTime();
                        @SuppressWarnings("unused")
                        final String dummy = String.valueOf(response);
                        appBlockHist.record((System.nanoTime() - appStart)
                                / NANO_TO_MS, attrs);
    
                        return response;
                    } catch (JedisConnectionException e) {
                        attempt++;
                        connErrorCounter.add(1, attrs);
                        retryCounter.add(1, attrs);
                        span.recordException(e);
                        if (attempt >= MAX_RETRIES) {
                            throw e;
                        }
                        try {
                            Thread.sleep((long) (Math.pow(2, attempt)
                                    * RETRY_BACKOFF_BASE_MS));
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }
                return null;
            } finally {
                span.end();
            }
        }
    }
  3. מריצים את האפליקציה למשך דקה לפחות כדי לתת למייצא מספיק זמן לאסוף את המדדים שפורסמו ולשלוח אותם ל-Monitoring.

Node.js

  1. כדי להתקין את יחסי התלות הנדרשים של OpenTelemetry ושל כלי הייצוא של OTLP, מריצים את הפקודות הבאות בטרמינל:

      npm install redis@^4.6.0 \
      @grpc/grpc-js@^1.12.0 \
      google-auth-library@^9.15.0 \
      @opentelemetry/api@^1.9.0 \
      @opentelemetry/sdk-trace-node@^2.1.0 \
      @opentelemetry/sdk-trace-base@^2.1.0 \
      @opentelemetry/sdk-metrics@^2.1.0 \
      @opentelemetry/instrumentation@^0.205.0 \
      @opentelemetry/instrumentation-redis@^0.67.0 \
      @opentelemetry/exporter-trace-otlp-grpc@^0.205.0 \
      @opentelemetry/exporter-metrics-otlp-grpc@^0.205.0 \
      @opentelemetry/resources@^2.10.0 \
      @opentelemetry/resource-detector-gcp@^0.40.0
  2. כדי להפעיל את המדדים בצד הלקוח, יוצרים קובץ server.js ומוסיפים לו את הקוד הבא:

    
    'use strict';
    
    const grpc = require('@grpc/grpc-js');
    const {trace, metrics} = require('@opentelemetry/api');
    const {
      OTLPMetricExporter,
    } = require('@opentelemetry/exporter-metrics-otlp-grpc');
    const {OTLPTraceExporter} = require('@opentelemetry/exporter-trace-otlp-grpc');
    const {registerInstrumentations} = require('@opentelemetry/instrumentation');
    const {RedisInstrumentation} = require('@opentelemetry/instrumentation-redis');
    const {gcpDetector} = require('@opentelemetry/resource-detector-gcp');
    const {defaultResource, detectResources} = require('@opentelemetry/resources');
    const {
      MeterProvider,
      PeriodicExportingMetricReader,
    } = require('@opentelemetry/sdk-metrics');
    const {BatchSpanProcessor} = require('@opentelemetry/sdk-trace-base');
    const {NodeTracerProvider} = require('@opentelemetry/sdk-trace-node');
    const {GoogleAuth} = require('google-auth-library');
    const {performance} = require('perf_hooks');
    
    const auth = new GoogleAuth({
      scopes: 'https://www.googleapis.com/auth/cloud-platform',
    });
    
    const channelCreds = grpc.credentials.combineChannelCredentials(
      grpc.credentials.createSsl(),
      grpc.credentials.createFromGoogleCredential({
        getRequestHeaders: async url => {
          const headers = await auth.getRequestHeaders(url);
          return typeof headers.entries === 'function'
            ? Object.fromEntries(headers.entries())
            : headers;
        },
      })
    );
    
    const projectDetector = {
      detect: () => ({
        attributes: {
          'gcp.project_id': auth.getProjectId().catch(() => undefined),
        },
      }),
    };
    
    const resource = defaultResource().merge(
      detectResources({detectors: [gcpDetector, projectDetector]})
    );
    
    const traceExporter = new OTLPTraceExporter({
      url: 'https://telemetry.googleapis.com:443',
      credentials: channelCreds,
    });
    
    const provider = new NodeTracerProvider({
      resource,
      spanProcessors: [new BatchSpanProcessor(traceExporter)],
    });
    provider.register();
    
    registerInstrumentations({
      instrumentations: [new RedisInstrumentation()],
    });
    
    const redis = require('redis');
    
    const metricExporter = new OTLPMetricExporter({
      url: 'https://telemetry.googleapis.com:443',
      credentials: channelCreds,
    });
    const metricReader = new PeriodicExportingMetricReader({
      exporter: metricExporter,
      exportIntervalMillis: 10000,
    });
    const meterProvider = new MeterProvider({
      resource,
      readers: [metricReader],
    });
    metrics.setGlobalMeterProvider(meterProvider);
    
    const tracer = trace.getTracer('redis.client.node');
    const meter = metrics.getMeter('redis.metrics.node');
    
    const rttHist = meter.createHistogram('redis_client_rtt', {unit: 'ms'});
    const appBlockHist = meter.createHistogram(
      'redis_application_blocking_latency',
      {unit: 'ms'}
    );
    const retryCounter = meter.createCounter('redis_retry_count');
    const connErrorCounter = meter.createCounter('redis_connectivity_error_count');
    
    retryCounter.add(0, {operation: 'startup'});
    connErrorCounter.add(0, {operation: 'startup'});
    
    const REDISHOST = process.env.REDISHOST || 'localhost';
    const REDISPORT = process.env.REDISPORT || 6379;
    
    const client = redis.createClient({
      socket: {
        host: REDISHOST,
        port: REDISPORT,
        reconnectStrategy: retries => {
          connErrorCounter.add(1, {error: 'socket_reconnect'});
          if (retries > 5) return new Error('Max retries reached');
          return Math.min(retries * 100, 3000);
        },
      },
    });
    client.on('error', err => console.log('Redis Client Error', err));
    
    async function smartRedisCall(operationName, func, ...args) {
      let attempt = 0;
      while (attempt < 3) {
        try {
          const reqStart = performance.now();
          const response = await func(...args);
          rttHist.record(performance.now() - reqStart, {operation: operationName});
    
          const appParseStart = performance.now();
          // eslint-disable-next-line no-unused-vars
          const _ = String(response);
          appBlockHist.record(performance.now() - appParseStart, {
            operation: operationName,
          });
    
          return response;
        } catch (e) {
          attempt++;
          retryCounter.add(1, {operation: operationName});
          if (attempt >= 3) throw e;
          await new Promise(resolve =>
            setTimeout(resolve, Math.pow(2, attempt) * 100)
          );
        }
      }
    }
    
    async function main() {
      if (typeof resource.waitForAsyncAttributes === 'function') {
        await resource.waitForAsyncAttributes();
      }
      await client.connect();
    
      await tracer.startActiveSpan('process_user_span', async span => {
        try {
          // Simple write and read operations
          await smartRedisCall(
            'set_user',
            client.set.bind(client),
            'user:123',
            'active'
          );
    
          const result = await smartRedisCall(
            'get_user',
            client.get.bind(client),
            'user:123'
          );
          console.log('Retrieved:', result);
        } catch (e) {
          span.recordException(e);
        } finally {
          span.end();
        }
      });
    
      await client.quit();
      await provider.forceFlush();
      await meterProvider.forceFlush();
    }
    
    // Only run the script automatically if it is executed directly (e.g. `node server.js`)
    if (require.main === module) {
      main().catch(console.error);
    }
    
    // Export for testability
    module.exports = {
      main,
      smartRedisCall,
    };
    
  3. מריצים את האפליקציה למשך דקה לפחות כדי לתת למייצא מספיק זמן לאסוף את המדדים שפורסמו ולשלוח אותם ל-Monitoring.

Python

  1. כדי להתקין את יחסי התלות הנדרשים של OpenTelemetry ושל כלי הייצוא של OTLP, מריצים את הפקודות הבאות בטרמינל:

      pip install redis>=5.0.0 \
      opentelemetry-api==1.39.1 \
      opentelemetry-sdk==1.39.1 \
      opentelemetry-instrumentation-redis==0.60b1 \
      opentelemetry-exporter-otlp-proto-grpc \
      opentelemetry-resourcedetector-gcp \
      google-auth \
      requests \
      grpcio
  2. כדי להפעיל את המדדים בצד הלקוח, יוצרים קובץ main.py ומוסיפים את הקוד הבא לאפליקציה:

    import os
    import time
    
    import google.auth
    from google.auth.transport.grpc import AuthMetadataPlugin
    import google.auth.transport.requests
    import grpc
    from opentelemetry import metrics, trace
    from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import (
        OTLPMetricExporter,
    )
    from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
        OTLPSpanExporter,
    )
    from opentelemetry.instrumentation.redis import RedisInstrumentor
    from opentelemetry.resourcedetector.gcp_resource_detector import (
        GoogleCloudResourceDetector,
    )
    from opentelemetry.sdk.metrics import MeterProvider
    from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
    from opentelemetry.sdk.resources import get_aggregated_resources, Resource
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor
    import redis
    from redis.exceptions import ConnectionError, TimeoutError
    
    
    def init_telemetry():
        """Initializes OpenTelemetry with OTLP Exporters and returns the SDK objects."""
        credentials, project_id = google.auth.default(
            scopes=["https://www.googleapis.com/auth/cloud-platform"]
        )
        request = google.auth.transport.requests.Request()
        auth_metadata_plugin = AuthMetadataPlugin(credentials=credentials, request=request)
        channel_creds = grpc.composite_channel_credentials(
            grpc.ssl_channel_credentials(),
            grpc.metadata_call_credentials(auth_metadata_plugin),
        )
    
        resource = get_aggregated_resources([GoogleCloudResourceDetector()])
        if project_id:
            resource = resource.merge(Resource.create({"gcp.project_id": project_id}))
    
        # 1. Initialize Tracing
        tracer_provider = TracerProvider(resource=resource)
        tracer_provider.add_span_processor(
            BatchSpanProcessor(
                OTLPSpanExporter(
                    endpoint="telemetry.googleapis.com:443",
                    credentials=channel_creds,
                )
            )
        )
        trace.set_tracer_provider(tracer_provider)
        tracer = trace.get_tracer("redis.client")
    
        # 2. Initialize Metrics
        metrics_exporter = OTLPMetricExporter(
            endpoint="telemetry.googleapis.com:443",
            credentials=channel_creds,
        )
        metric_reader = PeriodicExportingMetricReader(
            metrics_exporter, export_interval_millis=10000
        )
        meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])
        metrics.set_meter_provider(meter_provider)
        meter = metrics.get_meter("redis.metrics")
    
        # Bundle all metric handlers safely into a dictionary
        redis_metrics = {
            "rtt_hist": meter.create_histogram("redis_client_rtt", unit="ms"),
            "client_block_hist": meter.create_histogram(
                "redis_client_blocking_latency", unit="ms"
            ),
            "app_block_hist": meter.create_histogram(
                "redis_application_blocking_latency", unit="ms"
            ),
            "retry_counter": meter.create_counter("redis_retry_count"),
            "conn_error_counter": meter.create_counter("redis_connectivity_error_count"),
        }
    
        redis_metrics["retry_counter"].add(0, {"operation": "startup"})
        redis_metrics["conn_error_counter"].add(0, {"operation": "startup"})
    
        # 3. Setup Redis Auto-Instrumentation
        RedisInstrumentor().instrument()
    
        return tracer, redis_metrics, tracer_provider, meter_provider
    
    
    def init_redis_pool():
        """Initializes and returns the Redis ConnectionPool and Client."""
        redis_host = os.environ.get("REDISHOST", "localhost")
        redis_port = int(os.environ.get("REDISPORT", 6379))
    
        redis_pool = redis.ConnectionPool(
            host=redis_host,
            port=redis_port,
            max_connections=10,
            decode_responses=True,
        )
        redis_client = redis.Redis(connection_pool=redis_pool)
        return redis_pool, redis_client
    
    
    def smart_redis_call(operation_name, func, redis_pool, metrics, *args, **kwargs):
        """Executes a Redis operation with metrics and retry handling (No Globals!)."""
        max_retries = 3
        attempt = 0
    
        pool_start = time.time()
        try:
            conn = redis_pool.get_connection()
            redis_pool.release(conn)
        except Exception:
            pass
    
        if metrics and metrics.get("client_block_hist"):
            metrics["client_block_hist"].record(
                (time.time() - pool_start) * 1000, {"operation": operation_name}
            )
    
        while attempt < max_retries:
            try:
                req_start = time.time()
                response = func(*args, **kwargs)
    
                if metrics and metrics.get("rtt_hist"):
                    metrics["rtt_hist"].record(
                        (time.time() - req_start) * 1000,
                        {"operation": operation_name},
                    )
    
                app_start = time.time()
                _ = str(response)
    
                if metrics and metrics.get("app_block_hist"):
                    metrics["app_block_hist"].record(
                        (time.time() - app_start) * 1000,
                        {"operation": operation_name},
                    )
    
                return response
    
            except (ConnectionError, TimeoutError) as e:
                attempt += 1
                if metrics and metrics.get("conn_error_counter"):
                    metrics["conn_error_counter"].add(1, {"operation": operation_name})
                if metrics and metrics.get("retry_counter"):
                    metrics["retry_counter"].add(1, {"operation": operation_name})
                if attempt >= max_retries:
                    raise e
                time.sleep((2**attempt) * 0.1)
    
    
    if __name__ == "__main__":
        tracer, redis_metrics, tracer_provider, meter_provider = init_telemetry()
        redis_pool, redis_client = init_redis_pool()
    
        if tracer:
            with tracer.start_as_current_span("process_user_span"):
                try:
                    # Simple write and read operations
                    smart_redis_call(
                        "set_user",
                        redis_client.set,
                        redis_pool,
                        redis_metrics,
                        "user:123",
                        "active",
                    )
    
                    result = smart_redis_call(
                        "get_user",
                        redis_client.get,
                        redis_pool,
                        redis_metrics,
                        "user:123",
                    )
                    print(f"Retrieved: {result}")
                except Exception as e:
                    print(f"Error: {e}")
    
            tracer_provider.shutdown()
            meter_provider.shutdown()
  3. מריצים את האפליקציה למשך דקה לפחות כדי לתת למייצא מספיק זמן לאסוף את המדדים שפורסמו ולשלוח אותם ל-Monitoring.

הצגת מדדים ב-Monitoring

אחרי שמפעילים את המדדים בצד הלקוח ומריצים את האפליקציה במשך דקה לפחות, כדי לתת למייצא מספיק זמן לאסוף ולשלוח מדדים ל-Monitoring, משתמשים ב-Monitoring כדי להציג את המדדים, לקבץ אותם לפי פעולה או מכונה ולהחיל צבירות כדי לעקוב אחרי ביצועי האפליקציה.

כדי לראות את המדדים ב-Monitoring:

  1. נכנסים לדף Metrics explorer במסוף Google Cloud .

    לדף Metrics Explorer

  2. בוחרים את הפרויקט ב- Google Cloud .

  3. לוחצים על בחירת מדד.

  4. חיפוש של workload.googleapis.com/redis.

  5. בוחרים מדד בצד הלקוח. מקבלים את הנתונים לפי operation ו-instance לפי הצורך, ובוחרים צובר. אפשרויות נוספות מפורטות במאמר איך בוחרים מדדים כשמשתמשים ב-Metrics Explorer.

הצגת מעקבים מבוזרים ב-Trace

אחרי שהאפליקציה מתחילה לייצא נתונים, אפשר להשתמש ב-Trace כדי להציג באופן חזותי את מחזור הבקשה-תגובה המלא של פקודות Redis. הצגת המעקבים המבוזרים ב-Trace מאפשרת לכם לאבחן צווארי בקבוק, כדי שתוכלו לבודד במהירות את המקור המדויק של זמן האחזור באפליקציה.

כדי להציג מעקבים מבוזרים ב-Trace:

  1. נכנסים לדף Trace explorer במסוף Google Cloud .

    כניסה ל-Trace Explorer

  2. בוחרים מעקב אחרון שמיוצג על ידי נקודה בתרשים הפיזור.

  3. בודקים את תצוגת ה-Waterfall כדי לבודד את מקור זמן הטעינה על ידי זיהוי צווארי הבקבוק הבאים:

    • משך הבקשה הכולל: הסרגל ברמה העליונה (הורה) מציג את משך הזמן הכולל שצריך להמתין עד לסיום הפעולה.

    • זמן האחזור של הרשת והשרת (RTT): הפסים המשניים (כמו אלה שמסומנים ב-GET או ב-SET) מציגים את הזמן שנדרש לפקודה לעבור ברשת ולרוץ בשרת Memorystore for Redis.

    • חסימת חיבור לקוח: אם יש פער אופקי גדול וריק לפני שמתחיל ה-span הצאצא של Redis, אז ה-thread של האפליקציה תקוע וממתין לחיבור TCP זמין ממאגר החיבורים.

    • חסימה של ניתוח האפליקציה: אם יש פער אופקי גדול וריק אחרי שה-span הצאצא של Redis מסתיים, סימן שהאפליקציה מתקשה לנתח או לעבד את המטען הייעודי (payload) שהוחזר. זה קורה לעיתים קרובות עם מחרוזות JSON בגודל של כמה מגה-בייט.

    • ניסיונות חוזרים: אם אתם רואים כמה טווחי משנה קצרים לאותה פקודה שמתרחשים ברצף באותו מעקב הורה, יכול להיות שהלקוח חווה אובדן מנות ברשת וצריך להפעיל את לולאת הניסיון החוזר של ההשהיה המעריכית לפני ניסיון חוזר (exponential backoff).

פתרון בעיות

בקטע הזה מפורטות בעיות נפוצות בביצועים שאפשר לזהות באמצעות מדדים בצד הלקוח, מוסבר מהן הסיבות העיקריות לבעיות האלה וניתנות הנחיות לפתרון הבעיות.

שגיאה מטרה פתרון בעיות

באפליקציה יש עלייה פתאומית בזמן האחזור, אבל נראה ש-Memorystore for Redis תקין לחלוטין.

  • ‫workload.googleapis.com/
    redis_client_blocking_latency
    (מדד בצד הלקוח): עלייה חדה
  • workload.googleapis.com/redis_client_rtt (מדד בצד הלקוח): נמוך או רגיל
  • redis.googleapis.com/commands/
    usec_per_call
    (מדד שרת Memorystore for Redis): נמוך או אופייני
  • redis.googleapis.com/clients/connected (מדד של שרת Memorystore for Redis): קו אופקי במספר מסוים
צוואר הבקבוק נמצא בתוך האפליקציה. השרשורים מנסים להריץ פקודות Redis, אבל מאגר החיבורים מנוצל במלואו. הערך הגבוה של redis_client_blocking_latency מייצג את הזמן שבו הקוד ממתין לשקע TCP זמין לפני שהפקודה נשלחת לרשת. כדי לטפל בתנועה הגבוהה יותר בו-זמנית, מגדילים את מגבלות הגודל של מאגר החיבורים בהגדרות של לקוח Redis (לדוגמה, MaxActive ל-Go,‏ MaxTotal ל-Java או max_connections ל-Node.js ול-Python).

הבקשה הושלמה, אבל נקודת הקצה נמשכת הרבה יותר זמן מהצפוי. אין בעיות שקשורות לתקינות של הרשת או השרת.

  • ‫workload.googleapis.com/
    redis_application_blocking_latency
    (מדד בצד הלקוח): עלייה חדה
  • workload.googleapis.com/redis_client_rtt (מדד בצד הלקוח): נמוך או רגיל
  • redis.googleapis.com/commands/
    usec_per_call
    (מדד שרת Memorystore for Redis): נמוך או אופייני
  • redis.googleapis.com/stats/
    network_traffic
    (Bytes out) (מדד של שרת Memorystore for Redis): עליות חדות
‫Memorystore for Redis מריץ את הפקודה והרשת מעבירה את המטען הייעודי (payload) במהירות (זמן הלוך ושוב קצר). עם זאת, המטען הייעודי שמוחזר הוא גדול (לדוגמה, מחרוזת JSON בגודל 15MB). באפליקציה יש redis_application_blocking_latency גבוה כי היא צורכת יותר מדי משאבים בזמן הקצאת הזיכרון וההסרה של המחרוזת הגדולה הזו מהסדרה לאובייקט. מבצעים אופטימיזציה של מודל הנתונים. אל תאחסנו אובייקטים גדולים של JSON במפתחות בודדים. מפרקים את הנתונים באמצעות פונקציות גיבוב (hash) של Redis (HSET) ומשתמשים ב-HGET או ב-HMGET כדי לאחזר רק את השדות הספציפיים שצריך.

הזמן שלוקח לאפליקציה להגיב למשתמשים מתארך, אבל במדדים של Redis מדווח על זמן תגובה קצר של השרת ועל מספר רגיל של בקשות למאגר החיבורים.

  • ‫workload.googleapis.com/redis_retry_count (מדד בצד הלקוח): קפיצות חדות
  • workload.googleapis.com/
    redis_connectivity_error_count
    (מדד בצד הלקוח): יכול להיות שיוצגו עליות זמניות
  • workload.googleapis.com/redis_client_rtt (מדד בצד הלקוח): נמוך או אופייני לבקשות שהצליחו
  • redis.googleapis.com/commands/
    usec_per_call
    (מדד שרת Memorystore for Redis): נמוך או אופייני
‫redis_client_rtt מתעד רק את ה-RTT של בקשות שהצליחו, ולכן הוא לא משקף את משך הזמן הקצוב לתפוגה של חבילה שנכשלה. כשהאפליקציה חווה אובדן מנות זמני או איפוסים של TCP, לוגיקת הניסיון החוזר של הלקוח המדווח מגדילה את redis_retry_count ומפעילה את לולאת ההשהיה המעריכית לפני ניסיון חוזר (exponential backoff). הפעולה הזו גורמת לזמן המתנה בין הניסיונות (לדוגמה, 100ms, 200ms או 400ms). המשתמש חווה זמן אחזור כולל גבוה, אבל שורש הבעיה הוא אובדן מנות ברשת, שגורם לעיכובים בהמתנה בצד הלקוח. בודקים ביומני הזרימה של VPC אם יש חבילות שנמחקו, הגבלת רוחב פס או חריגות בניתוב בין אזורים. אם אתם נתקלים בבעיות של זמן קצוב לתפוגה, ודאו שזמן הקצוב לתפוגה של חיבור הלקוח (socket_timeout או connect_timeout) גדול מה-RTT הצפוי, כדי להביא בחשבון את התנודות הזמניות ברשת.

הכול נעצר וכל השכבות של צינור עיבוד הנתונים של הטלמטריה מדווחות על זמן אחזור ארוך.

  • ‫workload.googleapis.com/redis_client_rtt (מדד בצד הלקוח): גבוה
  • redis.googleapis.com/commands/
    usec_per_call
    (מדד השרת של Memorystore for Redis): גבוה
  • redis.googleapis.com/stats/
    cpu_utilization_main_thread
    (מדד של שרת Memorystore for Redis): גבוה (לדוגמה, קרוב ל-1 s/s או ל-100%)
  • תרשים מפל של מעקב: מוצגת פקודה שלוקחת הרבה זמן
‫Redis הוא single-threaded. כשמריצים פקודה עם מורכבות זמן של O(N), כמו KEYS *, SMEMBERS על קבוצה גדולה או HGETALL על גיבוב עם מיליוני שדות, מנוע Redis מושהה כדי למלא את הבקשה. בזמן שהפקודה הזו פועלת, כל בקשה אחרת של האפליקציה נכנסת לתור, וכתוצאה מכך יש עלייה חדה בזמן האחזור בכל המערכת. מכיוון שהערך של redis_client_rtt בהתאמה אישית תואם לזמן האחזור של השרת (commands/usec_per_call), השרת שמריץ את הפקודה הוא צוואר הבקבוק.

פותחים את Trace ומסתכלים על פקודות Redis בפרקי הזמן האיטיים כדי לזהות איזו שאילתה גורמת לחסימה. החליפו פקודות חסימה בפקודות ללא חסימה בקוד.

כדי לעבור על מערכי נתונים גדולים באופן מצטבר בלי לנעול את השרשור של השרת, משתמשים ב-SCAN, ב-SSCAN או ב-HSCAN.

באפליקציה מדווח על זמן אחזור בסיסי גבוה ועקבי לכל פקודות Redis, גם כשתעבורת הנתונים נמוכה.

  • ‫workload.googleapis.com/redis_client_rtt (מדד בצד הלקוח): גבוה באופן עקבי (p50 ו-p99 הם בערך 30-100ms+‎)
  • ‫redis.googleapis.com/commands/
    usec_per_call
    (מדד שרת Memorystore for Redis): נמוך מאוד (פחות מ-1ms)
  • ‫workload.googleapis.com/
    redis_client_blocking_latency

    ו-redis_application_blocking_latency: נמוכה או רגילה
שרת Redis מריץ פקודות באופן מיידי, אבל האפליקציה והמכונה פרוסות באזורים שונים (לדוגמה, us-central1 ו-us-east1). כל חבילת נתונים ברשת צריכה לעבור בתשתית הענן הפיזית של Google Cloud בין מרכזי הנתונים הגיאוגרפיים האלה. התוצאה היא זמן אחזור חובה בין אזורים במהירות האור לכל נסיעה הלוך ושוב. כדי לצמצם את זמן האחזור, כדאי לפרוס את האפליקציה כך שתהיה באותו אזור ובאותו תחום כמו המכונה. כדי לראות את האזור של האפליקציה והמכונה, משתמשים במסוף Google Cloud .

המאמרים הבאים