<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by shaqwieer on Medium]]></title>
        <description><![CDATA[Stories by shaqwieer on Medium]]></description>
        <link>https://medium.com/@mohamedkhaledshaqwieer?source=rss-4c36ccae7ce5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4FIGe7uAAiUEtDH4DYmQLw.jpeg</url>
            <title>Stories by shaqwieer on Medium</title>
            <link>https://medium.com/@mohamedkhaledshaqwieer?source=rss-4c36ccae7ce5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:08:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohamedkhaledshaqwieer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Bleeding Performance: The Ultimate Guide to EF Core with Massive Datasets]]></title>
            <link>https://medium.com/@mohamedkhaledshaqwieer/stop-bleeding-performance-the-ultimate-guide-to-ef-core-with-massive-datasets-98f6e8efde92?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/98f6e8efde92</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 22:42:57 GMT</pubDate>
            <atom:updated>2026-02-21T22:47:02.973Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>How to tame Entity Framework Core when your database has millions of rows — and why your LINQ queries might be silently destroying your SQL Server.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*3WLp4WCqm0_P0QrFf0jRWg.jpeg" /></figure><p>If you’ve ever watched a production API crawl to a halt because Entity Framework Core decided to generate a many tables JOIN or a WHERE clause with many parameters, this article is for <strong>you</strong>.</p><p>EF Core is a powerful ORM. But power without discipline is chaos. When you’re dealing with <strong>massive datasets</strong> — millions of rows, complex queries, multi-tenant systems — the default “it just works” approach will betray you.</p><blockquote>This guide covers the hard-won lessons for making EF Core perform at scale: from query optimization and SQL expansion mitigation to bulk operations and architecture patterns that keep your database healthy.</blockquote><h3>1. Understand What EF Core Is Actually Doing</h3><p>Before optimizing anything, you need visibility. Every LINQ query you write gets translated into SQL, and that translation isn’t always what you expect.</p><h4>Enable Query Logging in Development</h4><pre>optionsBuilder<br>    .UseNpgsql(connectionString)<br>    .LogTo(Console.WriteLine, LogLevel.Information)<br>    .EnableSensitiveDataLogging()  // Shows parameter values<br>    .EnableDetailedErrors();</pre><p>Or better yet, use <strong>query tags</strong> to trace slow queries back to the exact line of code:</p><pre>var orders = await context.Orders<br>    .TagWith(&quot;GetPendingOrders - OrderService.cs:42&quot;)<br>    .Where(o =&gt; o.Status == OrderStatus.Pending)<br>    .ToListAsync();</pre><p>When you see a query taking 8 seconds in your logs, you’ll know exactly where to look.</p><h4>Use ToQueryString() for Debugging</h4><pre>var query = context.Products<br>    .Where(p =&gt; p.Price &gt; 100)<br>    .OrderBy(p =&gt; p.Name);<br><br>Console.WriteLine(query.ToQueryString());</pre><p>This prints the exact SQL that EF Core will generate — invaluable for catching problems before they hit production.</p><h3>2. The No-Tracking Revolution</h3><p>By default, EF Core tracks every entity it loads. For read-heavy workloads (which is most workloads), this is pure waste.</p><h4>Set No-Tracking as the Default</h4><pre>// In your DbContext configuration<br>services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>    options.UseNpgsql(connectionString)<br>           .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));</pre><p>Then opt-in to tracking only when you actually need to modify entities:</p><pre>// Only track when you need to update<br>var order = await context.Orders<br>    .AsTracking()<br>    .FirstOrDefaultAsync(o =&gt; o.Id == orderId);<br><br>order.Status = OrderStatus.Shipped;<br>await context.SaveChangesAsync();</pre><p><strong>The impact is real.</strong> On a dataset of 100K entities, no-tracking queries can be 2–3x faster and consume significantly less memory because EF Core doesn’t need to maintain change tracking snapshots.</p><h3>3. Projection: Stop Loading What You Don’t Need</h3><p>This is the single most impactful optimization most developers miss. Loading full entities when you only need three fields is like downloading an entire movie to watch the trailer.</p><h4>Bad: Loading Full Entities</h4><pre>// Loads ALL columns, creates full entity objects, tracks them<br>var customers = await context.Customers<br>    .Where(c =&gt; c.IsActive)<br>    .ToListAsync();<br><br>return customers.Select(c =&gt; new { c.Name, c.Email });</pre><h4>Good: Project at the Database Level</h4><pre>// Only selects Name and Email columns in SQL<br>var customers = await context.Customers<br>    .Where(c =&gt; c.IsActive)<br>    .Select(c =&gt; new CustomerDto<br>    {<br>        Name = c.Name,<br>        Email = c.Email<br>    })<br>    .ToListAsync();</pre><p>The second version generates a SELECT Name, Email FROM Customers instead of SELECT *. With wide tables (20+ columns, JSON fields, binary data), the difference is dramatic.</p><h4>Use DTOs Aggressively</h4><p>Create purpose-built DTOs for every query scenario:</p><pre>public record OrderSummaryDto(<br>    int OrderId,<br>    string CustomerName,<br>    decimal Total,<br>    int ItemCount);<br><br>var summaries = await context.Orders<br>    .Where(o =&gt; o.CreatedAt &gt;= startDate)<br>    .Select(o =&gt; new OrderSummaryDto(<br>        o.Id,<br>        o.Customer.Name,<br>        o.OrderItems.Sum(i =&gt; i.Price * i.Quantity),<br>        o.OrderItems.Count()))<br>    .ToListAsync();</pre><blockquote>EF Core is smart enough to translate Sum() and Count() inside projections into SQL aggregates. Use this — it means the database does the heavy lifting, not your application server.</blockquote><h3>4. SQL Expansion: The Silent Performance Killer</h3><p><strong>SQL expansion</strong> is one of the most dangerous performance traps in EF Core, and many developers don’t even know it exists.</p><h4>What Is SQL Expansion?</h4><p>SQL expansion occurs when EF Core translates a seemingly simple LINQ operation into unexpectedly verbose or complex SQL. The most notorious case is the Contains method with large collections.</p><pre>var customerIds = GetCustomerIds(); // Returns 5,000 IDs<br><br>var orders = await context.Orders<br>    .Where(o =&gt; customerIds.Contains(o.CustomerId))<br>    .ToListAsync();</pre><p>EF Core translates this into:</p><pre>SELECT * FROM Orders<br>WHERE CustomerId IN (1, 2, 3, 4, 5, ... /* 5,000 literal values */)</pre><p>This creates several problems: the SQL string itself becomes enormous (potentially megabytes), SQL Server’s query plan cache gets polluted because each different set of IDs creates a unique query plan, and some databases have hard limits on the number of parameters (SQL Server caps at 2,100 parameters, PostgreSQL at 32,767).</p><h4>Mitigation Strategy 1: Use a Temporary Table or Table-Valued Parameter</h4><p>For SQL Server, use a table-valued parameter approach:</p><pre>// Create a DataTable for the IDs<br>var idTable = new DataTable();<br>idTable.Columns.Add(&quot;Id&quot;, typeof(int));<br>foreach (var id in customerIds)<br>    idTable.Rows.Add(id);<br><br>// Use raw SQL with TVP<br>var orders = await context.Orders<br>    .FromSqlRaw(@&quot;<br>        SELECT o.* FROM Orders o<br>        INNER JOIN @ids i ON o.CustomerId = i.Id&quot;,<br>        new SqlParameter(&quot;@ids&quot;, SqlDbType.Structured)<br>        {<br>            TypeName = &quot;dbo.IntIdList&quot;,<br>            Value = idTable<br>        })<br>    .ToListAsync();</pre><p>For PostgreSQL, you can use the ANY operator with an array parameter:</p><pre>var orders = await context.Orders<br>    .FromSqlInterpolated($@&quot;<br>        SELECT * FROM &quot;&quot;Orders&quot;&quot;<br>        WHERE &quot;&quot;CustomerId&quot;&quot; = ANY({customerIds.ToArray()})&quot;)<br>    .ToListAsync();</pre><h4>Mitigation Strategy 2: Batch the Contains Calls</h4><p>If you can’t use raw SQL, break the collection into smaller batches:</p><pre>public static async Task&lt;List&lt;T&gt;&gt; BatchContainsQuery&lt;T&gt;(<br>    IQueryable&lt;T&gt; baseQuery,<br>    IEnumerable&lt;int&gt; ids,<br>    Expression&lt;Func&lt;T, int&gt;&gt; idSelector,<br>    int batchSize = 500)<br>{<br>    var results = new List&lt;T&gt;();<br>    var batches = ids.Chunk(batchSize);<br><br>    foreach (var batch in batches)<br>    {<br>        var batchList = batch.ToList();<br>        var batchResults = await baseQuery<br>            .Where(BuildContainsExpression(idSelector, batchList))<br>            .ToListAsync();<br>        results.AddRange(batchResults);<br>    }<br><br>    return results;<br>}</pre><h4>Mitigation Strategy 3: Use EF Core 8+ Primitive Collections</h4><p>EF Core 8 introduced <strong>primitive collection support</strong>, which dramatically improves how Contains is translated:</p><pre>// EF Core 8+ translates this more efficiently using OPENJSON (SQL Server)<br>// or unnest (PostgreSQL) instead of expanding into literals<br>var customerIds = new List&lt;int&gt; { 1, 2, 3, /* ... */ };<br><br>var orders = await context.Orders<br>    .Where(o =&gt; customerIds.Contains(o.CustomerId))<br>    .ToListAsync();<br><br>// SQL Server output (EF Core 8+):<br>// SELECT * FROM Orders<br>// WHERE CustomerId IN (SELECT [value] FROM OPENJSON(@__ids_0))</pre><p><strong>This is a game-changer.</strong> Upgrade to EF Core 8+ if you haven’t already, just for this feature alone.</p><h4>Other SQL Expansion Traps to Watch For</h4><p><strong>Nullable comparisons</strong> can cause expression tree bloat:</p><pre>// If TenantId is nullable, EF Core generates complex COALESCE logic<br>.Where(x =&gt; x.TenantId == tenantId)<br><br>// Generated SQL might be:<br>// WHERE (TenantId = @p0) OR (TenantId IS NULL AND @p0 IS NULL)</pre><p><strong>Fix:</strong> Use non-nullable types where possible, or be explicit:</p><pre>.Where(x =&gt; x.TenantId != null &amp;&amp; x.TenantId == tenantId)</pre><p><strong>String operations</strong> like Contains, StartsWith, and EndsWith can also expand unpredictably depending on your database provider and collation settings. Always verify the generated SQL.</p><h3>5. Pagination Done Right</h3><p>Never use .Skip().Take() with large offsets. The database still has to scan through all the skipped rows.</p><h4>Bad: Offset-Based Pagination</h4><pre>// Page 500: DB scans 50,000 rows to skip them, then returns 100<br>var page = await context.Products<br>    .OrderBy(p =&gt; p.Id)<br>    .Skip(50_000)<br>    .Take(100)<br>    .ToListAsync();</pre><h4>Good: Keyset (Cursor-Based) Pagination</h4><pre>// Page 500: DB seeks directly to the cursor position<br>var page = await context.Products<br>    .Where(p =&gt; p.Id &gt; lastSeenId) // Cursor-based: instant seek<br>    .OrderBy(p =&gt; p.Id)<br>    .Take(100)<br>    .ToListAsync();</pre><p>Keyset pagination performs consistently regardless of how deep you are in the dataset. The WHERE Id &gt; @cursor clause uses an index seek, which is O(log n) instead of O(n).</p><h3>6. Bulk Operations: EF Core Is Not a Bulk Tool (But You Can Make It One)</h3><p>EF Core’s SaveChangesAsync() generates individual INSERT, UPDATE, or DELETE statements for each entity. For 10,000 entities, that&#39;s 10,000 round-trips to the database.</p><h4>Use ExecuteUpdate and ExecuteDelete (EF Core 7+)</h4><pre>// Update 50,000 rows in a single SQL statement<br>await context.Products<br>    .Where(p =&gt; p.Category == &quot;Discontinued&quot;)<br>    .ExecuteUpdateAsync(s =&gt; s<br>        .SetProperty(p =&gt; p.IsActive, false)<br>        .SetProperty(p =&gt; p.ModifiedAt, DateTime.UtcNow));<br><br>// Delete 30,000 rows in a single SQL statement<br>await context.AuditLogs<br>    .Where(a =&gt; a.CreatedAt &lt; cutoffDate)<br>    .ExecuteDeleteAsync();</pre><p>These bypass the change tracker entirely and execute as a single SQL statement. The performance difference is orders of magnitude.</p><h4>For Massive Inserts, Use Specialized Libraries</h4><p>For inserting tens of thousands of rows, use dedicated bulk libraries:</p><pre>// Using EFCore.BulkExtensions (popular NuGet package)<br>var products = GenerateProducts(100_000);<br>await context.BulkInsertAsync(products);<br><br>// Or for PostgreSQL, use Npgsql&#39;s COPY protocol<br>await using var writer = await connection.BeginBinaryImportAsync(<br>    &quot;COPY products (name, price, category) FROM STDIN (FORMAT BINARY)&quot;);<br><br>foreach (var product in products)<br>{<br>    await writer.StartRowAsync();<br>    await writer.WriteAsync(product.Name, NpgsqlDbType.Text);<br>    await writer.WriteAsync(product.Price, NpgsqlDbType.Numeric);<br>    await writer.WriteAsync(product.Category, NpgsqlDbType.Text);<br>}<br><br>await writer.CompleteAsync();</pre><h3>7. Split Queries: Tame the Cartesian Explosion</h3><p>When you include multiple collections, EF Core generates a single massive JOIN that creates a cartesian product:</p><pre>// Single query mode: creates cartesian explosion<br>var orders = await context.Orders<br>    .Include(o =&gt; o.OrderItems)<br>    .Include(o =&gt; o.Payments)<br>    .Include(o =&gt; o.ShippingDetails)<br>    .ToListAsync();</pre><p>If an order has 10 items, 3 payments, and 2 shipping records, the single query returns 10 × 3 × 2 = 60 rows per order. With 1,000 orders, that’s 60,000 rows of mostly duplicated data.</p><h4>Use AsSplitQuery()</h4><pre>var orders = await context.Orders<br>    .Include(o =&gt; o.OrderItems)<br>    .Include(o =&gt; o.Payments)<br>    .Include(o =&gt; o.ShippingDetails)<br>    .AsSplitQuery()  // Executes separate queries for each Include<br>    .ToListAsync();</pre><p>This generates 4 separate, lean queries instead of one bloated one. The trade-off is additional round-trips, but the total data transferred is dramatically less.</p><p>You can also set this globally:</p><pre>optionsBuilder.UseNpgsql(connectionString,<br>    o =&gt; o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));</pre><blockquote><strong>When You Should NOT Use AsSplitQuery()</strong></blockquote><blockquote>❌ Simple queries<br> ❌ Latency-sensitive APIs<br> ❌ Strong consistency required<br> ❌ Small datasets<br> ❌ High-frequency endpoints</blockquote><h3>8. Global Query Filters: Essential but Treacherous</h3><p>Global query filters are excellent for multi-tenant systems and soft deletes, but they come with performance gotchas.</p><pre>// In your DbContext<br>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Order&gt;()<br>        .HasQueryFilter(o =&gt; o.TenantId == _currentTenantId);<br><br>    modelBuilder.Entity&lt;Product&gt;()<br>        .HasQueryFilter(p =&gt; !p.IsDeleted);<br>}</pre><h4>The Hidden Cost</h4><p>Global filters are applied to <strong>every query</strong>, including JOINs. If you join 5 filtered tables, you get 5 additional WHERE clauses. Ensure every filtered column has an index:</p><pre>modelBuilder.Entity&lt;Order&gt;(entity =&gt;<br>{<br>    entity.HasIndex(o =&gt; o.TenantId);<br>    entity.HasIndex(o =&gt; new { o.TenantId, o.Status }); // Composite for common queries<br>});</pre><h4>When to Bypass Filters</h4><pre>// Admin queries that need to see all tenants<br>var allOrders = await context.Orders<br>    .IgnoreQueryFilters()<br>    .Where(o =&gt; o.Status == OrderStatus.Failed)<br>    .ToListAsync();</pre><p>Use IgnoreQueryFilters() judiciously for cross-tenant reporting, data migration scripts, and administrative dashboards.</p><h3>9. Connection and Context Lifetime Management</h3><h4>Use DbContext Pooling</h4><pre>// Instead of AddDbContext, use AddDbContextPool<br>services.AddDbContextPool&lt;AppDbContext&gt;(options =&gt;<br>    options.UseNpgsql(connectionString),<br>    poolSize: 128);  // Adjust based on your workload</pre><p>Context pooling reuses DbContext instances instead of creating new ones for each request. This eliminates the overhead of model building and connection setup.</p><h4>Avoid Long-Lived Contexts</h4><p>A DbContext should live for the duration of a single unit of work (usually one HTTP request). Long-lived contexts accumulate tracked entities, consume memory, and return stale data:</p><pre>// WRONG: Singleton context<br>services.AddSingleton&lt;AppDbContext&gt;(); // Never do this<br><br>// RIGHT: Scoped context (one per request)<br>services.AddDbContextPool&lt;AppDbContext&gt;(options =&gt; ...);</pre><h3>10. Raw SQL: Know When to Drop Down</h3><p>EF Core is not the right tool for every query. For complex reporting, analytics, or performance-critical operations, use raw SQL or stored procedures without guilt:</p><pre>// Complex aggregation that would be awkward in LINQ<br>var report = await context.Database<br>    .SqlQueryRaw&lt;SalesReportDto&gt;(@&quot;<br>        SELECT<br>            DATE_TRUNC(&#39;month&#39;, o.created_at) AS Month,<br>            COUNT(DISTINCT o.customer_id) AS UniqueCustomers,<br>            SUM(oi.price * oi.quantity) AS Revenue,<br>            AVG(oi.price * oi.quantity) AS AvgOrderValue<br>        FROM orders o<br>        JOIN order_items oi ON o.id = oi.order_id<br>        WHERE o.created_at &gt;= @startDate<br>        GROUP BY DATE_TRUNC(&#39;month&#39;, o.created_at)<br>        ORDER BY Month&quot;,<br>        new NpgsqlParameter(&quot;@startDate&quot;, startDate))<br>    .ToListAsync();</pre><p>There’s no shame in using raw SQL. The best developers know which tool to use for each job.</p><h3>The Performance Checklist</h3><p>Before shipping any EF Core code that touches large datasets, run through this checklist:</p><p><strong>Query Level:</strong></p><ul><li>Are you projecting to DTOs instead of loading full entities?</li><li>Are read queries using AsNoTracking()?</li><li>Have you checked the generated SQL with ToQueryString()?</li><li>Are you using keyset pagination instead of offset-based?</li><li>Are Contains() calls using EF Core 8+ or batched?</li><li>Are multi-collection includes using AsSplitQuery()?</li></ul><p><strong>Data Modification:</strong></p><ul><li>Are bulk updates using ExecuteUpdateAsync() / ExecuteDeleteAsync()?</li><li>Are bulk inserts using dedicated libraries or COPY?</li></ul><p><strong>Infrastructure:</strong></p><ul><li>Is DbContext pooling enabled?</li><li>Are all filtered columns indexed?</li><li>Are compiled queries used for hot paths?</li><li>Is query logging enabled in development?</li></ul><h3>Final Thoughts</h3><p>EF Core is a fantastic tool that can absolutely handle massive datasets — but only if you respect the abstraction boundary. Know what SQL your LINQ generates. Understand when tracking helps and when it hurts. Batch your operations. And never, ever, send 10,000 IDs inside a Contains() call on EF Core 7 or below.</p><p>The difference between a sluggish API and a blazing-fast one often isn’t the database, the hardware, or the framework. It’s whether the developer took the time to understand what’s happening beneath the abstraction.</p><p><strong>Your database will thank you.</strong></p><p>If you found this guide helpful, give it a clap 👏 and follow for more deep dives into .NET performance and architecture. Got a war story about EF Core performance? Drop it in the comments — I’d love to hear it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98f6e8efde92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Disk: A Guide to In-Memory Databases and Redis Data Types.]]></title>
            <link>https://medium.com/@mohamedkhaledshaqwieer/beyond-the-disk-a-guide-to-in-memory-databases-and-redis-data-types-b32f300e3dcb?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b32f300e3dcb</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Sat, 07 Feb 2026 08:21:24 GMT</pubDate>
            <atom:updated>2026-02-07T08:23:17.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beyond the Disk: A Guide to In-Memory Databases and Redis Data Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NoFffYghp7y9BW-CFmLww.png" /></figure><p><strong>Introduction to In-Memory Databases</strong></p><ul><li><strong>Definition</strong>: An in-memory database (IMDB) stores data directly in the computer’s main memory (RAM) rather than on traditional disk storage, enabling faster data access and lower latency. (Figure 1)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7zlLZv36PyrZTavTMdl9A.png" /><figcaption>Figure 1</figcaption></figure><h4><strong>Key Differences Between Disk-Based and In-Memory Databases:</strong></h4><blockquote><strong>1. Storage: Disk-First vs. RAM-First</strong></blockquote><p>The fundamental difference starts with where your data “lives” when the system is running.</p><ul><li><strong>Regular Databases:</strong> These are designed to store data on physical disks (using engines like <strong>InnoDB</strong>). While they are smart enough to cache limited data in memory for quick access, the disk remains the primary home for your information.</li><li><strong>In-Memory Databases:</strong> These flip the script by storing data directly in <strong>RAM</strong>. This allows for near-instant access, though they often include optional persistent storage on disk to ensure durability if the system restarts.</li></ul><blockquote><strong>2. Querying: Complexity vs. Efficiency</strong></blockquote><p>Because the storage mediums are different, the engines required to search through them are built differently as well.</p><ul><li><strong>Regular Databases:</strong> These utilize a sophisticated query processor and transaction manager. The goal is to maintain strict <strong>ACID compliance</strong> through complex optimizations, ensuring that data remains consistent even during heavy disk-writing operations.</li><li><strong>In-Memory Databases:</strong> These follow a similar logical process but are stripped down for speed. By utilizing <strong>simpler algorithms</strong> optimized for memory access, they bypass the heavy computational overhead required to manage disk-based data.</li></ul><blockquote>3. Performance: Latency and Throughput</blockquote><p>The physical reality of hardware dictates the end-user experience.</p><ul><li><strong>Regular Databases:</strong> These generally offer lower performance compared to memory-based systems. The physical act of reading from and writing to a disk (<strong>Disk I/O</strong>) introduces higher latency and more complex processing bottlenecks.</li><li><strong>In-Memory Databases:</strong> These offer the “gold standard” for speed. Because they rely on <strong>Memory I/O</strong>, they achieve significantly lower latency and much higher throughput, making them ideal for high-traffic applications</li></ul><h4><strong>Introducing Redis</strong></h4><ul><li>which stands for “Remote Dictionary Server”, First release 2009.</li><li>An open-source in-memory database project implementing a <strong>distributed</strong>, in-memory key-value store with optional durability.</li><li>Redis is an open source, in-memory data structure store<br> Can be used as Database, Cache, Message broker</li><li>NoSQL Key/Value store</li><li>Supports multiple data structures , Will Discuss Later.</li><li>Features like Transactions ,Pub/Sub ,Scalability / availability options</li></ul><h4><strong>Who uses Redis</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RruSo_GvAq7GlFImzpwR7w.png" /></figure><h4><strong>DATATYPES</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*usGRNxLatB9RKNPeb5ZtqA.png" /></figure><p>Choosing the right data structure is like choosing the right container in a kitchen — you wouldn’t store soup in a colander. Here is how the most common data types work in practice:</p><h4>String: The Universal Container</h4><ul><li><strong>Structure:</strong> A simple key-value pair.</li><li><strong>Real-life Example:</strong> A user’s “About Me” bio or a session ID.</li><li><strong>Easy Visualization:</strong> user:101 -&gt; &quot;Hello World&quot;.</li></ul><h4>Hash: The Digital File Folder</h4><ul><li><strong>Structure:</strong> A collection of field-value pairs, perfect for objects.</li><li><strong>Real-life Example:</strong> A User Profile containing a name and city.</li><li><strong>Easy Visualization:</strong> { name: &quot;Alice&quot;, city: &quot;New York&quot; }.</li></ul><h4>List: The Waiting Line</h4><ul><li><strong>Structure:</strong> A series of elements sorted by insertion order.</li><li><strong>Real-life Example:</strong> A “Recent Activities” feed where the newest action appears at the top.</li><li><strong>Easy Visualization:</strong> [ Post A &gt; Post B &gt; Post C ].</li></ul><h4>Set: The Unique Guest List</h4><ul><li><strong>Structure:</strong> An unordered collection of unique items.</li><li><strong>Real-life Example:</strong> Unique IP addresses visiting a website today (duplicates are automatically ignored).</li><li><strong>Easy Visualization:</strong> { User_A, User_B, User_C }.</li></ul><h4>Sorted Set: The Competition Leaderboard</h4><ul><li><strong>Structure:</strong> Similar to a Set, but every member is associated with a score for ranking.</li><li><strong>Real-life Example:</strong> An online gaming leaderboard where players are ranked by high scores.</li><li><strong>Easy Visualization:</strong> { Player_A: 1000, Player_B: 850 }.</li></ul><h4>Bitmap &amp; Bitfield: The Light Switch Array</h4><ul><li><strong>Structure:</strong> Extremely compact storage using bits (0 or 1).</li><li><strong>Real-life Example:</strong> Tracking daily user attendance (1 for “present,” 0 for “absent”) for a whole year in a tiny file.</li><li><strong>Easy Visualization:</strong> 01101101....</li></ul><h4>Geospatial: The Digital Map</h4><ul><li><strong>Structure:</strong> Stores longitude and latitude coordinates.</li><li><strong>Real-life Example:</strong> Finding the nearest ride-share driver to your current location.</li><li><strong>Easy Visualization:</strong> { Driver_1: (40.7, -74.0) }.</li></ul><h4>HyperLogLog: The Crowd Estimator</h4><ul><li><strong>Structure:</strong> A probabilistic algorithm used to count unique things with very little memory.</li><li><strong>Real-life Example:</strong> Estimating how many millions of unique users searched for a specific keyword today.</li></ul><h4>Stream: The Security Camera Feed</h4><ul><li><strong>Structure:</strong> An append-only log that records events as they happen.</li><li><strong>Real-life Example:</strong> A financial transaction log or a live chat message history.</li><li><strong>Easy Visualization:</strong> { id_1: &quot;Transaction Start&quot;, id_2: &quot;Payment Processed&quot; }.</li></ul><blockquote><strong>A Note on Modern Web Standards</strong></blockquote><p>While all these specialized types exist, it is important to note that <strong>most web applications primarily use the String type to store data</strong>.</p><p>Instead of mapping every object field to a Hash, developers often take a complex data object, turn it into a string (known as <strong>Serialization</strong>, like converting an object to a JSON string), and store it. When the data is needed, the application retrieves the string and converts it back into an object (known as <strong>Deserialization</strong>). This approach simplifies the code and is highly efficient for standard application needs.</p><p><em>“Do you prefer storing JSON strings or using native Redis Hashes?”</em></p><p><strong>Let me know in the comments!</strong></p><pre>// 1. Our complex data object<br>const userProfile = {<br>    id: 42,<br>    username: &quot;dev_explorer&quot;,<br>    preferences: {<br>        theme: &quot;dark&quot;,<br>        notifications: true<br>    }<br>};<br><br>// 2. SERIALIZATION<br>// We turn the object into a JSON String so the database can store it easily.<br>const serializedData = JSON.stringify(userProfile); <br><br>console.log(&quot;Stored in DB as:&quot;, serializedData);<br>// Output: &#39;{&quot;id&quot;:42,&quot;username&quot;:&quot;dev_explorer&quot;,&quot;preferences&quot;:{&quot;theme&quot;:&quot;dark&quot;,&quot;notifications&quot;:true}}&#39;<br><br><br>// --- Later, when we fetch the data back from the DB ---<br><br><br>// 3. DESERIALIZATION<br>// We turn the String back into a usable JavaScript Object.<br>const fetchedData = JSON.parse(serializedData);<br><br>console.log(&quot;Back to Object:&quot;, fetchedData.username); <br>// Output: dev_explorer</pre><p>in next time , we will discuss advanced topics in redis like <strong>Persistence , Transactions , Pub/Sub , practical code examples.</strong></p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> if the article helped you ! 👏</em></li><li><em>Follow us on </em><a href="https://eg.linkedin.com/in/shaqwieer"><em>LinkedIn</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b32f300e3dcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explaining Events And Listeners And Subscribers Using Easy Examples in Laravel]]></title>
            <link>https://medium.com/@mohamedkhaledshaqwieer/explaining-events-and-listeners-and-subscribers-using-easy-examples-in-laravel-65c8538f317e?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/65c8538f317e</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 06:46:14 GMT</pubDate>
            <atom:updated>2023-10-27T06:46:14.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMpCevLnKzd_YYCAAazQaA.jpeg" /></figure><blockquote><strong>Let’s imagine a blogging platform where:</strong></blockquote><ol><li>Users can write and publish articles.</li><li>Whenever an article is published, an event is fired.</li><li>There are listeners who perform actions such as sending notifications or updating analytics when the event is fired.</li><li>There’s also a subscriber that handles various article-related events.</li></ol><h3>Creating an Event:</h3><p>Let’s create an event for when an article is published.</p><pre>php artisan make:event ArticlePublished</pre><p>This will create the ArticlePublished event in the app/Events directory:</p><pre>namespace App\Events;<br><br>use Illuminate\Broadcasting\InteractsWithSockets;<br>use Illuminate\Foundation\Events\Dispatchable;<br>use Illuminate\Queue\SerializesModels;<br>use App\Models\Article;<br><br>class ArticlePublished<br>{<br>    use Dispatchable, InteractsWithSockets, SerializesModels;<br><br>    public $article;<br><br>    public function __construct(Article $article)<br>    {<br>        $this-&gt;article = $article;<br>    }<br>}</pre><h3>Creating Listeners:</h3><p>We’ll create two listeners: one for sending notifications and another for updating analytics.</p><pre>php artisan make:listener SendNotificationForPublishedArticle --event=ArticlePublished<br>php artisan make:listener UpdateAnalyticsForPublishedArticle --event=ArticlePublished</pre><p>SendNotificationForPublishedArticle:</p><pre>namespace App\Listeners;<br><br>use App\Events\ArticlePublished;<br><br>class SendNotificationForPublishedArticle<br>{<br>    public function handle(ArticlePublished $event)<br>    {<br>        // Logic to send notifications<br>        // $event-&gt;article provides access to the article data<br>    }<br>}</pre><h3>Registering Event &amp; Listeners:</h3><p>Register the event and its listeners in EventServiceProvider:</p><pre>protected $listen = [<br>    ArticlePublished::class =&gt; [<br>        SendNotificationForPublishedArticle::class,<br>        UpdateAnalyticsForPublishedArticle::class,<br>    ],<br>];</pre><h3>Creating a Subscriber:</h3><p>The subscriber will handle multiple article-related events. Let’s create the subscriber:</p><pre>php artisan make:listener ArticleEventSubscriber</pre><p>Now, define the subscriber’s logic:</p><pre>namespace App\Listeners;<br><br>class ArticleEventSubscriber<br>{<br>    public function onArticlePublished($event)<br>    {<br>        // Handle the ArticlePublished event.<br>    }<br><br>    public function onArticleDeleted($event)<br>    {<br>        // Handle the ArticleDeleted event.<br>    }<br><br>    public function subscribe($events)<br>    {<br>        $events-&gt;listen(<br>            &#39;App\Events\ArticlePublished&#39;,<br>            &#39;App\Listeners\ArticleEventSubscriber@onArticlePublished&#39;<br>        );<br><br>        $events-&gt;listen(<br>            &#39;App\Events\ArticleDeleted&#39;,<br>            &#39;App\Listeners\ArticleEventSubscriber@onArticleDeleted&#39;<br>        );<br>    }<br>}</pre><p>Register this subscriber in the EventServiceProvider:</p><pre>protected $subscribe = [<br>    &#39;App\Listeners\ArticleEventSubscriber&#39;,<br>];</pre><h3>Firing the Event:</h3><p>When an article is published, you can fire the event:</p><pre>use App\Events\ArticlePublished;<br><br>// Assume $article is an instance of the Article model that was just published<br>event(new ArticlePublished($article));</pre><p>When this event is fired, the SendNotificationForPublishedArticle and UpdateAnalyticsForPublishedArticle listeners will be triggered. If there were other article-related events, the ArticleEventSubscriber would handle them as well.</p><p>This system allows you to keep your application logic clean and decoupled, ensuring each part of your app does one thing and does it well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65c8538f317e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service Container And Service Provider Is Explained Easily In Laravel]]></title>
            <link>https://medium.com/@mohamedkhaledshaqwieer/service-container-and-service-provider-is-explained-easily-in-laravel-9f8442dee641?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f8442dee641</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[advanced]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 12:22:05 GMT</pubDate>
            <atom:updated>2023-10-26T12:22:05.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMpCevLnKzd_YYCAAazQaA.jpeg" /></figure><p>let’s use a real-world analogy paired with code to explain the concepts of the Service Container and Service Providers.</p><h3>Real-World Analogy: Coffee Shop ☕</h3><p>Imagine you’re setting up a coffee shop.</p><ol><li>Service Container: This is like the storage room of your coffee shop. It’s where you store the raw materials like coffee beans, milk, sugar, etc. When you need any of these items, you go to the storage room to get them. The storage room knows exactly where each item is located and provides it to you.</li><li>Service Providers: These are your coffee recipes and equipment setup instructions. They guide how to make a specific type of coffee (like an espresso, latte, or cappuccino) and how to set up and calibrate your coffee machines. It sets up the “services” your coffee shop offers.</li></ol><h3>Laravel Application: Coffee Shop ☕</h3><p><strong>Service Container:</strong> Manages the creation of objects/services.</p><blockquote>Binding a Service:</blockquote><pre>// When I ask for &#39;CoffeeBeans&#39;, give me this particular brand.<br>$this-&gt;app-&gt;bind(&#39;CoffeeBeans&#39;, function() {<br>    return new BrandXBeans();<br>});</pre><blockquote>Resolving a Service:</blockquote><pre>// I need coffee beans for this order.<br>$beans = $this-&gt;app-&gt;make(&#39;CoffeeBeans&#39;);</pre><p><strong>Service Providers:</strong> Bootstraps and configures the application components.</p><blockquote>Registering Services:</blockquote><pre>public function register()<br>{<br>    // Registering how to make an Espresso.<br>    $this-&gt;app-&gt;bind(&#39;Espresso&#39;, function($app) {<br>        $beans = $app-&gt;make(&#39;CoffeeBeans&#39;);<br>        return new Espresso($beans);<br>    });<br>}</pre><blockquote>Bootstrapping:</blockquote><pre>public function boot()<br>{<br>    // Calibrating the coffee machine every time the shop opens.<br>    CoffeeMachine::calibrate();<br>}</pre><h3>Workflow:</h3><ol><li><strong>Morning Setup:</strong> As you start your day in the coffee shop, you follow the coffee recipes and machine setup instructions (Service Providers bootstrapping your shop).</li><li><strong>During the Day:</strong> When a customer orders an espresso, you go to the storage room to get the coffee beans (Service Container providing you the beans). Then, you make the espresso-based on the recipe (Service Provider has already registered how to make an espresso). If another customer asks for a latte, the process repeats, but this time, you also get milk from the storage room (Service Container).</li></ol><p>In essence, the <strong>Service Container</strong> is your go-to place to get resources and services. The <strong>Service Providers </strong>are the setup and recipe guides, ensuring everything is available and set correctly for making coffees (or running your application).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f8442dee641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explaining Queue And Background Processing Using Real-Life Example]]></title>
            <link>https://medium.com/@mohamedkhaledshaqwieer/explaining-queue-and-background-processing-using-real-life-example-1bff22231b5b?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bff22231b5b</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 12:11:09 GMT</pubDate>
            <atom:updated>2023-10-26T12:11:09.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVID70yIBO7zCwc6cxo_OQ.jpeg" /></figure><p>Let’s imagine a real-life scenario where a queue would be incredibly beneficial.</p><h3>Scenario: Photo Sharing Platform</h3><p>Imagine you’re building a web platform similar to Instagram where users can upload photos, apply filters, and then share them with followers.</p><h3><strong>Features &amp; Challenges:</strong></h3><ol><li>Photo Upload: Users can upload high-resolution photos.</li><li>Photo Processing: After upload, photos need to be:</li></ol><ul><li>Resized to multiple dimensions for thumbnails, mobile views, and desktop views.</li><li>Processed to apply user-selected filters.</li><li>Checked for any content that violates the platform’s terms of service using an AI service.</li></ul><p>These processes, especially resizing and AI checking, can be time-consuming. If done synchronously, the user would have to wait a long time after uploading a photo before getting any feedback. This would be a poor user experience.</p><blockquote>The solution is making a queue for this tasks and worker work with the stored jobs</blockquote><h3>Steps:</h3><p><strong>1. Set Up a Database Queue</strong></p><p>First, you’d probably set up a database queue for simplicity. Later, you might switch to Redis or another driver for scalability.</p><p>Run:</p><pre>php artisan queue:table<br>php artisan migrate</pre><p><strong>2. Create a Job for Processing the Photo</strong></p><p>Generate a new job:</p><pre>php artisan make:job ProcessPhoto</pre><p>The job might look something like this:</p><pre>// app/Jobs/ProcessPhoto.php<br><br>namespace App\Jobs;<br><br>use App\Models\Photo;<br>use Illuminate\Bus\Queueable;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Foundation\Bus\Dispatchable;<br>use Illuminate\Queue\InteractsWithQueue;<br>use Illuminate\Queue\SerializesModels;<br><br>class ProcessPhoto implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br><br>    protected $photo;<br><br>    public function __construct(Photo $photo)<br>    {<br>        $this-&gt;photo = $photo;<br>    }<br><br>    public function handle()<br>    {<br>        // Resize the photo for various dimensions<br>        $this-&gt;resizePhoto($this-&gt;photo-&gt;file_path);<br><br>        // Apply user-selected filter<br>        $this-&gt;applyFilter($this-&gt;photo-&gt;filter, $this-&gt;photo-&gt;file_path);<br><br>        // Check content with AI service (assuming a hypothetical checkContentWithAI() method)<br>        if ($this-&gt;checkContentWithAI($this-&gt;photo-&gt;file_path)) {<br>            // Notify the user if content violates terms (this could be an email or in-app notification)<br>            $this-&gt;notifyUserOfViolation($this-&gt;photo-&gt;user);<br>        } else {<br>            // Mark photo as processed and live on the platform<br>            $this-&gt;photo-&gt;status = &#39;processed&#39;;<br>            $this-&gt;photo-&gt;save();<br>            <br>            // Notify the user that their photo is now live<br>            $this-&gt;notifyUserOfSuccess($this-&gt;photo-&gt;user);<br>        }<br>    }<br>}</pre><p><strong>3. Dispatching the Job</strong></p><p>When a user uploads a photo:</p><pre>use App\Jobs\ProcessPhoto;<br><br>public function upload(Request $request)<br>{<br>    $photo = new Photo;<br>    // Assume the file is stored and the path is set to $photo-&gt;file_path and other properties are set...<br><br>    $photo-&gt;save();<br><br>    // Dispatch the job to process the photo<br>    ProcessPhoto::dispatch($photo);<br><br>    return response()-&gt;json([&#39;message&#39; =&gt; &#39;Photo uploaded and is being processed.&#39;]);<br>}</pre><p><strong>4. Running the Queue Worker</strong></p><p>In production, you’d keep a worker running to process queued jobs:</p><pre>php artisan queue:work</pre><p>Remember, this is a simplified example. In a real-world scenario, you’d have more intricate error handling, perhaps utilize events/listeners for notifications, handle job failures more gracefully, and you’d likely use more sophisticated storage and processing libraries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bff22231b5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where do You Place The Remember Function Or Any Caching Logic In Laravel?]]></title>
            <link>https://medium.com/@mohamedkhaledshaqwieer/where-you-place-the-remember-function-or-any-caching-logic-in-laravel-819aef42d0ff?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/819aef42d0ff</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 11:51:24 GMT</pubDate>
            <atom:updated>2023-10-26T11:56:17.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMpCevLnKzd_YYCAAazQaA.jpeg" /></figure><p>In a Laravel project, where you place the remember function or any caching logic depends on the architecture, organization, and best practices you&#39;re adhering to. However, here are some common places and situations where caching logic can be used.</p><h3>1. Controllers:</h3><p>The most straightforward place to implement caching is within controllers, especially if the caching logic directly pertains to data being passed to a view.</p><pre>// In a CelebrityController, for instance<br>public function show($id)<br>{<br>    $celebrityProfile = Cache::remember(&quot;celebrity_profile_{$id}&quot;, 120, function () use ($id) {<br>        // Fetch and return the profile data<br>    });<br><br>    return view(&#39;celebrity.show&#39;, [&#39;profile&#39; =&gt; $celebrityProfile]);<br>}</pre><h3>2. Eloquent Models:</h3><p>If you find that you’re frequently caching specific queries or data related to an Eloquent model, you might implement the caching logic in a custom method on the model itself or a related service class.</p><pre>class Celebrity extends Model<br>{<br>    public static function getCachedProfile($id)<br>    {<br>        return Cache::remember(&quot;celebrity_profile_{$id}&quot;, 120, function () use ($id) {<br>            return self::with(&#39;works&#39;, &#39;events&#39;, &#39;comments&#39;)-&gt;find($id);<br>        });<br>    }<br>}</pre><p>Then in your controller or wherever needed:</p><pre>$profile = Celebrity::getCachedProfile($id);</pre><h3>3. Service Classes:</h3><p>For more complex applications, it’s a good practice to offload business logic from controllers into service classes. These classes can encapsulate specific business rules and caching strategies.</p><pre>class CelebrityService<br>{<br>    public function getProfile($id)<br>    {<br>        return Cache::remember(&quot;celebrity_profile_{$id}&quot;, 120, function () use ($id) {<br>            // Fetch and return the profile data<br>        });<br>    }<br>}</pre><p>You can then inject or instantiate this service in your controller or command to use its methods.</p><h3>4. Repository Pattern:</h3><p>If you’re using the repository pattern, caching can be an integral part of your repositories. Repositories abstract the data access layer, making it a suitable place for caching database results.</p><h3>5. Middleware:</h3><p>Though less common for this type of caching, middlewares can be used for caching full responses or parts of responses in certain scenarios.</p><h3>6. Jobs &amp; Commands:</h3><p>If you’re pre-caching data or warming up the cache as part of a scheduled task or command, then the logic might reside in a Laravel command or job class.</p><blockquote><strong>Note</strong></blockquote><p>Remember, while caching can improve performance, it also introduces a layer of complexity. Always have a clear strategy on cache invalidation, and ensure that the cached data does not become stale, leading to outdated data being served to users. Wherever you place the caching logic, make sure it’s organized and maintainable, especially if you’re working within a team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=819aef42d0ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching Explaining In Laravel Using Real-Life Example]]></title>
            <link>https://medium.com/@mohamedkhaledshaqwieer/caching-explaining-in-laravel-using-real-life-example-8bc1d7ef6d24?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bc1d7ef6d24</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 11:40:45 GMT</pubDate>
            <atom:updated>2023-10-26T11:40:45.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SngdEZhL0j5tFKIA-oze7w.jpeg" /></figure><p>Let’s assume you’re running a website similar to IMDb or Wikipedia, where you showcase profiles of famous people like actors, musicians, politicians, etc. These profiles get millions of views, especially when these celebrities are trending due to recent events, movies, songs, or news.</p><h3>Scenario:</h3><p>Every celebrity profile page displays:</p><ol><li>Basic details like name, birthdate, biography.</li><li>A list of their recent works (movies, albums, books, etc.).</li><li>Upcoming events or appearances.</li><li>Fan comments or reviews.</li></ol><h3>Without Caching:</h3><p>Every time a user views a celebrity profile:</p><ul><li>The application queries the database for the celebrity’s basic details.</li><li>It fetches their recent works.</li><li>It checks for upcoming events or appearances.</li><li>It retrieves the latest fan comments or reviews.</li></ul><p>This approach would put immense strain on the database, especially for trending celebrities.</p><h3>With Caching using the remember function:</h3><p>When a user requests a celebrity profile, the system can utilize Laravel’s remember function to cache and retrieve the profile efficiently.</p><pre>use Illuminate\Support\Facades\Cache;<br><br>$celebrityId = 55; // example celebrity ID, this could be dynamic based on the profile being accessed.<br><br>$celebrityProfile = Cache::remember(&quot;celebrity_profile_{$celebrityId}&quot;, 120, function () use ($celebrityId) {<br>    return [<br>        &#39;details&#39; =&gt; Celebrity::find($celebrityId),<br>        &#39;recent_works&#39; =&gt; Work::where(&#39;celebrity_id&#39;, $celebrityId)-&gt;latest()-&gt;limit(5)-&gt;get(),<br>        &#39;upcoming_events&#39; =&gt; Event::where(&#39;celebrity_id&#39;, $celebrityId)-&gt;upcoming()-&gt;get(),<br>        &#39;latest_comments&#39; =&gt; Comment::where(&#39;celebrity_id&#39;, $celebrityId)-&gt;latest()-&gt;limit(10)-&gt;get()<br>    ];<br>});</pre><blockquote>Here’s how this works:</blockquote><ol><li>First, it checks if the profile data for the specified celebrity ID is already in the cache.</li><li>If yes, it returns the cached data immediately, bypassing all database queries.</li><li>If not, it compiles the profile data using multiple queries, stores this data in the cache for 120 minutes, and then returns the data.</li></ol><h3>Cache Invalidation:</h3><p>When there’s a significant update related to the celebrity (e.g., a new movie is added, an event date changes or the biography gets an update), you’d want to clear this cache to ensure users get the most updated profile.</p><pre>Cache::forget(&quot;celebrity_profile_{$celebrityId}&quot;);</pre><p>By using caching this way, the application can swiftly serve millions of profile views with minimal database interaction. It ensures that fans accessing the profiles get quick load times, and the server resources are used efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bc1d7ef6d24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack for Beginners with Examples]]></title>
            <link>https://medium.com/@mohamedkhaledshaqwieer/webpack-for-beginners-with-examples-fbec94a02e85?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbec94a02e85</guid>
            <category><![CDATA[enhancement]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 08:55:15 GMT</pubDate>
            <atom:updated>2023-10-16T08:55:15.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94ZhvvcXzyzCwuUVjxljhA.png" /></figure><p>Imagine you’re making a scrapbook. Each page of the scrapbook contains a story made up of photos, captions, stickers, and drawings. Your scrapbook is your website, and the individual items (photos, captions, etc.) are your different files (like JavaScript, CSS, and images).</p><p>Webpack is like a super-efficient scrapbook organizer. Instead of you manually cutting, pasting, and arranging each item on every page, Webpack does it for you</p><h4>Key Points About Webpack:</h4><blockquote><strong>Bundler</strong></blockquote><ul><li><strong>Without Webpack:</strong> Imagine you have to glue each photo, caption, and sticker individually onto each page of the scrapbook. It’s time-consuming!</li><li><strong>With Webpack: </strong>Webpack takes all your items and intelligently groups them for you, placing them neatly onto each page.</li><li><strong>Example:</strong> If you have 10 JavaScript files for your website, instead of loading them separately (which is slow), Webpack combines them into a single file.</li></ul><blockquote><strong>Loaders</strong></blockquote><ul><li><strong>Scenario:</strong> Some of your photos are too big for your scrapbook. You need to resize them.</li><li><strong>Without Webpack:</strong> You manually cut each photo to size.</li><li><strong>With Webpack (using Loaders):</strong> Webpack automatically resizes the photos for you.</li><li><strong>Example:</strong> You wrote your styles in SCSS (a special styling language). Browsers don’t understand SCSS, so a loader in Webpack converts SCSS to regular CSS, which browsers understand.</li></ul><blockquote><strong>Plugins</strong></blockquote><ul><li><strong>Scenario:</strong> You want to add a glossy finish to some pages of your scrapbook.</li><li><strong>Without Webpack:</strong> You manually apply the finish to each page.</li><li><strong>With Webpack (using Plugins): </strong>Webpack applies the glossy finish for you to the selected pages.</li><li><strong>Example:</strong> You want to compress your JavaScript to make it load faster on your website. A Webpack plugin can automatically do this compression for you.</li></ul><blockquote><strong>Development Server</strong></blockquote><ul><li><strong>Scenario:</strong> Every time you add a new item to your scrapbook, you want to instantly see how it looks without redoing the whole page.</li><li><strong>With Webpack’s Development Server:</strong> As soon as you place a new item, you instantly see it on the page without rearranging everything.</li><li><strong>Example:</strong> When building a website, every time you make a change in your code, you would normally have to refresh your browser to see the effect. With Webpack’s development server, the updates happen instantly.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbec94a02e85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference Between UseCases in Watcher And Computed in Vue 3]]></title>
            <link>https://blog.stackademic.com/difference-between-usecases-in-watcher-and-computed-in-vue-3-5a7764248949?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a7764248949</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 16:18:11 GMT</pubDate>
            <atom:updated>2023-10-25T01:25:30.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*CPDIH8BWrGipHRJ6o6E2Vw.png" /></figure><p>In Vue 3, both computed properties and watchers allow you to react to changes in reactive data, but they have distinct purposes and behaviors. Here’s a breakdown of their differences in terms of use cases:</p><h3>Computed Properties:</h3><blockquote><strong>Primary Use-case:</strong> .</blockquote><blockquote>To derive new data from existing reactive sources.</blockquote><blockquote><strong>Features &amp; Behavior:</strong></blockquote><ul><li><strong>Reactive</strong>: They react to changes in their dependencies.</li><li><strong>Cached</strong>: Only recalculates when dependencies change, which can be performance-optimized.</li><li><strong>Synchronous</strong>: Typically used for synchronous operations to transform data.</li><li><strong>Read-only by default</strong>: Though you can provide a setter to make them writable.</li></ul><blockquote><strong>Examples:</strong></blockquote><ul><li>Combining firstName and lastName into a fullName.</li><li>Calculating the total price of items in a cart.</li><li>Filtering a list of items based on a search query</li></ul><h3>Watchers:</h3><blockquote><strong>Primary Use Case:</strong></blockquote><blockquote>To execute side-effects in response to changes in reactive data.</blockquote><blockquote><strong>Features &amp; Behavior:</strong></blockquote><ul><li><strong>Observant</strong>: They observe changes in data and execute a function in response.</li><li><strong>Flexible</strong>: Can watch both individual reactive sources and computed properties.</li><li><strong>Handle Side-effects</strong>: Suitable for operations that have side-effects, such as API calls.</li><li><strong>Can be Asynchronous:</strong> You can perform asynchronous operations inside a watcher.</li></ul><blockquote><strong>Examples:</strong></blockquote><ul><li>Fetching additional data from an API when a user ID changes.</li><li>Saving data to local storage whenever it gets updated in the component.</li><li>Logging or analytics tracking based on specific data changes.</li></ul><h3>Practical Difference:</h3><p>Imagine you have a component where the user can input their firstName and lastName, and you want to display their full name and also fetch their profile when their userID changes.</p><p>Using <strong>computed:</strong></p><pre>import { ref, computed } from &#39;vue&#39;;<br><br>export default {<br>  setup() {<br>    const firstName = ref(&#39;John&#39;);<br>    const lastName = ref(&#39;Doe&#39;);<br><br>    const fullName = computed(() =&gt; {<br>      return `${firstName.value} ${lastName.value}`;<br>    });<br><br>    return { firstName, lastName, fullName };<br>  }<br>}</pre><p>Using <strong>watcher</strong>:</p><pre>import { ref, watch } from &#39;vue&#39;;<br><br>export default {<br>  setup() {<br>    const userID = ref(123);<br><br>    watch(userID, async (newID) =&gt; {<br>      // Fetch the user&#39;s profile when userID changes<br>      const profile = await fetchUserProfile(newID);<br>      // ... handle the profile data<br>    });<br><br>    return { userID };<br>  }<br>}</pre><p><strong>In Summary:</strong></p><ul><li>Computed properties are best suited for deriving or transforming data based on reactive sources. They are reactive and optimize performance by caching their results.</li><li>Watchers are best for reacting to data changes and introducing side effects, like making an API call, performing logs, or saving data elsewhere. They offer more generic control over reacting to data changes.</li></ul><p>In design and best practices, it’s often recommended to use computed properties for data transformation and watchers for side effects. However, the two can be used in conjunction to create powerful and dynamic applications.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a7764248949" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/difference-between-usecases-in-watcher-and-computed-in-vue-3-5a7764248949">Difference Between UseCases in Watcher And Computed in Vue 3</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming Paradigms Using JavaScript (JS) Examples]]></title>
            <link>https://medium.com/@mohamedkhaledshaqwieer/programming-paradigms-using-javascript-js-examples-27585386fb7e?source=rss-4c36ccae7ce5------2</link>
            <guid isPermaLink="false">https://medium.com/p/27585386fb7e</guid>
            <category><![CDATA[basics-of-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[paradigm]]></category>
            <category><![CDATA[imperative-programming]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <dc:creator><![CDATA[shaqwieer]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 05:38:56 GMT</pubDate>
            <atom:updated>2023-10-04T05:38:56.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*BDHS7s-U2QCsPS2mYQHdRQ.png" /><figcaption>Some Types Of Programming Paradigms in JS</figcaption></figure><h3>1. Procedural/Imperative Programming:</h3><blockquote>Principle:</blockquote><ul><li>This is a step-by-step approach to solving problems. It defines sequences of instructions that specify exactly what the computer should do.</li></ul><blockquote>JavaScript Example:</blockquote><pre>function add(a, b) {<br>    return a + b;<br>}<br><br>const result = add(5, 3);<br>console.log(&quot;The result is:&quot;, result);</pre><h3>2. Object-Oriented Programming (OOP):</h3><blockquote>Principle:</blockquote><ul><li>We organize code into objects with properties (attributes) and methods (functions). JS supports OOP with prototypal inheritance.</li></ul><blockquote>JavaScript Example:</blockquote><pre>class Animal {<br>    constructor(name) {<br>        this.name = name;<br>    }<br><br>    speak() {<br>        console.log(`I am an animal named ${this.name}`);<br>    }<br>}<br><br>class Dog extends Animal {<br>    speak() {<br>        console.log(`Woof! I am a dog named ${this.name}`);<br>    }<br>}<br><br>const myDog = new Dog(&quot;Buddy&quot;);<br>myDog.speak();  // Outputs: Woof! I am a dog named Buddy</pre><h3>3. Functional Programming:</h3><blockquote>Principle:</blockquote><ul><li>Emphasizes the use of pure functions, immutability, and first-class functions. Functions are treated as first-class citizens, meaning they can be passed as arguments, returned from other functions, and assigned to variables.</li></ul><blockquote>JavaScript Example:</blockquote><pre>const numbers = [1, 2, 3, 4, 5];<br><br>const squaredNumbers = numbers.map(num =&gt; num * num);<br><br>console.log(squaredNumbers); // Outputs: [1, 4, 9, 16, 25]</pre><h3>4. Event-Driven Programming:</h3><p>Principle:</p><ul><li>The flow of the program is determined by events (e.g., user interactions, I/O operations).</li></ul><p>JavaScript Example (For a browser environment):</p><pre>document.getElementById(&quot;myButton&quot;).addEventListener(&quot;click&quot;, function() {<br>    alert(&quot;Button was clicked!&quot;);<br>});</pre><h3>5. Reactive Programming:</h3><blockquote>Principle:</blockquote><ul><li>Deals with asynchronous data streams (observables) and the propagation of change. It’s often used in modern front-end frameworks.</li></ul><p>For JS, the most popular library for reactive programming is RxJS.</p><blockquote>JavaScript Example (Using RxJS):</blockquote><pre>const { fromEvent } = rxjs;<br><br>const buttonClicks = fromEvent(document.getElementById(&#39;myButton&#39;), &#39;click&#39;);<br><br>buttonClicks.subscribe(event =&gt; {<br>    console.log(&#39;Button was clicked!&#39;);<br>});</pre><h3>6. Declarative Programming:</h3><blockquote>Principle:</blockquote><ul><li>You tell the computer what you want, and it figures out how to achieve it. This paradigm is opposed to imperative programming, where you specify how to achieve the desired result.</li></ul><blockquote>JavaScript Example (Using array filter method):</blockquote><pre>const numbers = [1, 2, 3, 4, 5];<br>const evenNumbers = numbers.filter(n =&gt; n % 2 === 0);<br>console.log(evenNumbers); // Outputs: [2, 4]</pre><p>In this example, the filter method is declarative because you specify <em>what</em> you want (even numbers) and not <em>how</em> to filter them out of the array.</p><p>Each paradigm has a different approach to problem-solving and code organization. In real-world projects, especially in JavaScript, you might see a blend of multiple paradigms used to leverage the strengths of each.</p><h3>Summary:</h3><p>These examples are intended to be illustrative of each paradigm’s approach. As mentioned previously, it’s common to mix paradigms depending on the problem’s nature and the libraries or frameworks in use in real-world JavaScript development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27585386fb7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>