Skip to content

In-Memory Caching

Giriş

In-Memory Caching, verilerin uygulama belleğinde geçici olarak saklanması işlemidir. .NET'te IMemoryCache arayüzü ve MemoryCache sınıfı ile kolayca uygulanabilir.

In-Memory Caching'in Önemi

  1. Performans
  2. Veritabanı yükünü azaltma
  3. Yanıt sürelerini kısaltma
  4. CPU kullanımını optimize etme

  5. Ölçeklenebilirlik

  6. Uygulama yükünü dağıtma
  7. Kaynak kullanımını optimize etme
  8. Sistem kapasitesini artırma

  9. Maliyet

  10. Veritabanı maliyetlerini azaltma
  11. Ağ trafiğini azaltma
  12. İşlem maliyetlerini düşürme

In-Memory Caching Türleri

  1. MemoryCache
  2. Temel in-memory caching
  3. Thread-safe
  4. Expiration policies

  5. Distributed Memory Cache

  6. Birden fazla sunucu arasında paylaşım
  7. Yüksek ölçeklenebilirlik
  8. Fault tolerance

  9. Hybrid Cache

  10. Memory ve distributed cache kombinasyonu
  11. Esnek yapı
  12. Optimize edilmiş performans

In-Memory Caching Kullanımı

  1. Temel Kullanım

    public class CacheService
    {
        private readonly IMemoryCache _cache;
        private readonly MemoryCacheEntryOptions _options;
    
        public CacheService(IMemoryCache cache)
        {
            _cache = cache;
            _options = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(30))
                .SetAbsoluteExpiration(TimeSpan.FromHours(1));
        }
    
        public T GetOrCreate<T>(string key, Func<T> factory)
        {
            return _cache.GetOrCreate(key, entry =>
            {
                entry.SetOptions(_options);
                return factory();
            });
        }
    }
    

  2. Async Kullanım

    public class AsyncCacheService
    {
        private readonly IMemoryCache _cache;
        private readonly MemoryCacheEntryOptions _options;
    
        public AsyncCacheService(IMemoryCache cache)
        {
            _cache = cache;
            _options = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(30))
                .SetAbsoluteExpiration(TimeSpan.FromHours(1));
        }
    
        public async Task<T> GetOrCreateAsync<T>(string key, Func<Task<T>> factory)
        {
            if (_cache.TryGetValue(key, out T cachedValue))
            {
                return cachedValue;
            }
    
            var value = await factory();
            _cache.Set(key, value, _options);
            return value;
        }
    }
    

  3. Cache Invalidation

    public class CacheInvalidator
    {
        private readonly IMemoryCache _cache;
        private readonly ILogger<CacheInvalidator> _logger;
    
        public CacheInvalidator(IMemoryCache cache, ILogger<CacheInvalidator> logger)
        {
            _cache = cache;
            _logger = logger;
        }
    
        public void Invalidate(string key)
        {
            _cache.Remove(key);
            _logger.LogInformation("Cache invalidated for key: {Key}", key);
        }
    
        public void InvalidateByPattern(string pattern)
        {
            var keys = GetKeysByPattern(pattern);
            foreach (var key in keys)
            {
                Invalidate(key);
            }
        }
    }
    

In-Memory Caching Best Practices

  1. Cache Key Tasarımı
  2. Anlamlı ve tutarlı isimlendirme
  3. Namespace kullanımı
  4. Versiyonlama

  5. Expiration Stratejileri

  6. Sliding expiration
  7. Absolute expiration
  8. Priority-based expiration

  9. Memory Yönetimi

  10. Size limitleri
  11. Eviction politikaları
  12. Memory pressure handling

  13. Error Handling

  14. Fallback mekanizmaları
  15. Circuit breaker
  16. Retry politikaları

Mülakat Soruları

Temel Sorular

  1. In-Memory Caching nedir ve neden önemlidir?
  2. Cevap: In-Memory Caching, verilerin uygulama belleğinde geçici olarak saklanmasıdır. Performans iyileştirmesi, ölçeklenebilirlik ve maliyet optimizasyonu sağlar.

  3. MemoryCache ve Distributed Cache arasındaki farklar nelerdir?

  4. Cevap:

    • MemoryCache: Tek sunucuda, hızlı, uygulama içi
    • Distributed Cache: Birden fazla sunucuda, ölçeklenebilir, paylaşımlı
  5. Cache expiration stratejileri nelerdir?

  6. Cevap:

    • Sliding expiration
    • Absolute expiration
    • Priority-based expiration
    • Size-based expiration
  7. Cache invalidation stratejileri nelerdir?

  8. Cevap:

    • Zaman tabanlı
    • Olay tabanlı
    • Manuel invalidation
    • Dependency-based
  9. Cache coherency nedir?

  10. Cevap:
    • Önbellek tutarlılığı
    • Veri senkronizasyonu
    • Stale data önleme
    • Consistency modelleri

Teknik Sorular

  1. MemoryCache kullanımı nasıl yapılır?
  2. Cevap:

    public class MemoryCacheService
    {
        private readonly IMemoryCache _cache;
        private readonly MemoryCacheEntryOptions _options;
    
        public MemoryCacheService(IMemoryCache cache)
        {
            _cache = cache;
            _options = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(30))
                .SetAbsoluteExpiration(TimeSpan.FromHours(1));
        }
    
        public T GetOrCreate<T>(string key, Func<T> factory)
        {
            return _cache.GetOrCreate(key, entry =>
            {
                entry.SetOptions(_options);
                return factory();
            });
        }
    }
    

  3. Cache monitoring nasıl yapılır?

  4. Cevap:

    public class CacheMonitor
    {
        private readonly IMemoryCache _cache;
        private readonly ILogger<CacheMonitor> _logger;
    
        public CacheMonitor(IMemoryCache cache, ILogger<CacheMonitor> logger)
        {
            _cache = cache;
            _logger = logger;
        }
    
        public void LogCacheStatistics()
        {
            var stats = new
            {
                HitCount = _cache.GetCurrentStatistics()?.TotalHits ?? 0,
                MissCount = _cache.GetCurrentStatistics()?.TotalMisses ?? 0,
                CurrentSize = _cache.GetCurrentStatistics()?.CurrentEntryCount ?? 0
            };
    
            _logger.LogInformation("Cache Statistics: {@Stats}", stats);
        }
    }
    

  5. Cache fallback stratejisi nasıl uygulanır?

  6. Cevap:

    public class CacheWithFallback
    {
        private readonly IMemoryCache _cache;
        private readonly ILogger<CacheWithFallback> _logger;
    
        public CacheWithFallback(IMemoryCache cache, ILogger<CacheWithFallback> logger)
        {
            _cache = cache;
            _logger = logger;
        }
    
        public async Task<T> GetWithFallback<T>(string key, Func<Task<T>> factory, TimeSpan cacheDuration)
        {
            try
            {
                if (_cache.TryGetValue(key, out T cachedValue))
                {
                    return cachedValue;
                }
    
                var value = await factory();
                _cache.Set(key, value, cacheDuration);
                return value;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Cache operation failed for key: {Key}", key);
                return await factory();
            }
        }
    }
    

  7. Cache size yönetimi nasıl yapılır?

  8. Cevap:

    public class CacheSizeManager
    {
        private readonly IMemoryCache _cache;
        private readonly ILogger<CacheSizeManager> _logger;
        private readonly long _maxSize;
    
        public CacheSizeManager(IMemoryCache cache, ILogger<CacheSizeManager> logger, long maxSize)
        {
            _cache = cache;
            _logger = logger;
            _maxSize = maxSize;
        }
    
        public void EnsureCacheSize()
        {
            var currentSize = _cache.GetCurrentStatistics()?.CurrentSize ?? 0;
            if (currentSize > _maxSize)
            {
                _logger.LogWarning("Cache size exceeded limit: {CurrentSize}/{MaxSize}", currentSize, _maxSize);
                EvictOldestItems();
            }
        }
    
        private void EvictOldestItems()
        {
            // Implement oldest items eviction logic
        }
    }
    

  9. Cache warming nasıl yapılır?

  10. Cevap:
    public class CacheWarmer
    {
        private readonly IMemoryCache _cache;
        private readonly ILogger<CacheWarmer> _logger;
    
        public CacheWarmer(IMemoryCache cache, ILogger<CacheWarmer> logger)
        {
            _cache = cache;
            _logger = logger;
        }
    
        public async Task WarmCache<T>(string key, Func<Task<T>> factory, TimeSpan cacheDuration)
        {
            try
            {
                var value = await factory();
                _cache.Set(key, value, cacheDuration);
                _logger.LogInformation("Cache warmed for key: {Key}", key);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to warm cache for key: {Key}", key);
            }
        }
    }
    

İleri Seviye Sorular

  1. Cache coherency sorunları nasıl çözülür?
  2. Cevap:

    • Strong consistency modelleri
    • Eventual consistency
    • Versioning
    • Distributed locking
    • Cache synchronization
  3. Cache warming stratejileri nelerdir?

  4. Cevap:

    • Startup warming
    • Background warming
    • Predictive warming
    • Scheduled warming
    • On-demand warming
  5. Cache partitioning nasıl yapılır?

  6. Cevap:

    • Key-based partitioning
    • Hash-based partitioning
    • Range partitioning
    • Directory partitioning
    • Consistent hashing
  7. Cache monitoring ve alerting nasıl yapılır?

  8. Cevap:

    • Performance metrics
    • Hit/miss ratios
    • Memory usage
    • Latency monitoring
    • Custom alerts
  9. Cache security nasıl sağlanır?

  10. Cevap:
    • Encryption
    • Access control
    • Data isolation
    • Secure communication
    • Audit logging