<?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 Rohat Şahin on Medium]]></title>
        <description><![CDATA[Stories by Rohat Şahin on Medium]]></description>
        <link>https://medium.com/@rohatsahin?source=rss-928849028fc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ak7glzl1Hac2KIMfDe0Kxg.png</url>
            <title>Stories by Rohat Şahin on Medium</title>
            <link>https://medium.com/@rohatsahin?source=rss-928849028fc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:26:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohatsahin/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[Some Tips for Resolving SQL Query Performance Anomalies]]></title>
            <link>https://medium.com/@rohatsahin/some-tips-for-resolving-sql-query-performance-anomalies-6505c71972f9?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6505c71972f9</guid>
            <category><![CDATA[database-management]]></category>
            <category><![CDATA[rdms]]></category>
            <category><![CDATA[sql-query-analyzer]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[query-optimization]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 21:28:27 GMT</pubDate>
            <atom:updated>2025-06-01T21:28:27.030Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I will discuss how to determine whether our SQL queries are running efficiently. Performance issues with queries are common for application developers and can become serious problems in production systems. It’s important to understand and identify the root causes behind slow query execution.</p><ul><li><strong>Monitor shared buffer and cache hit ratio</strong></li></ul><p>The shared buffer is a main memory cache PostgreSQL uses for storing data pages. When your relational data fits in the entire memory, it means fewer disk reads and faster queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*HiDeXws5hKZaEYLA_o9Nvw.png" /><figcaption>an example for IO &amp; Buffer timins for scan operation</figcaption></figure><p>In the example above, we observe that when the dataset is too large to fit into memory or when available memory is insufficient, PostgreSQL must rely heavily on disk I/O. This results in significantly slower query performance and can lead to instability or unpredictability in execution time.</p><p>Some tips to track and create a monitor for your system to make an alert or observe:</p><p><strong>Buffer Hit Ratio</strong>:</p><ul><li>Indicates the proportion of data accessed from memory rather than disk. A high buffer hit ratio (close to 100%) suggests that most operations are served from RAM.</li></ul><pre>SELECT sum(heap_blks_hit) / (sum(heap_blks_hit) + sum(heap_blks_read)) AS cache_hit_ratio<br>FROM pg_statio_user_tables;</pre><p><strong>Disk I/O Stats</strong>:</p><ul><li>Use tools like iostat or database-specific statistics (pg_stat_io in PostgreSQL to confirm minimal disk activity.</li></ul><p><strong>Tune PostgreSQL Settings:</strong></p><ul><li><strong>shared_buffers</strong>: Allocate a significant portion of RAM for PostgreSQL&#39;s shared memory.</li></ul><pre>shared_buffers = 25% of total RAM  # Adjust based on workload</pre><ul><li><strong>Adjust Query Planner Cost Constants for Existing Database Resources</strong></li></ul><p>In PostgreSQL, the query planner uses two important cost parameters — seq_page_cost and random_page_cost — to estimate the relative expense of reading data from disk. These parameters guide the planner in choosing the most efficient access strategy for table data, such as whether to perform a sequential scan or use an index. By tuning these values, database administrators can influence how PostgreSQL optimizes queries, especially in environments with specific I/O characteristics or large data volumes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*G65JgUNUW-3_i6e2N5zyiw.png" /><figcaption>a example of seq scan to large tables</figcaption></figure><p>The sequential scan shown above is a good example of what to avoid when working with large tables. In such cases, use EXPLAIN (ANALYZE, BUFFERS) on your slow query to understand its execution plan. If you consistently observe sequential scans on large datasets, it&#39;s a strong indication that indexing, query rewriting, or planner tuning may be needed.</p><p>A sequential scan on a large table with low selectivity — where the query only targets a small portion of the data — is often inefficient. If a suitable index exists but is not being used, consider increasing seq_page_cost or decreasing it. random_page_cost to encourage the query planner to favor index scans. These cost parameters can also be adjusted at the transaction level</p><p><strong>Tune Settings in PostgreSQL:</strong></p><pre>BEGIN;<br>SET LOCAL seq_page_cost = 2.0;<br>-- your query here<br>COMMIT;</pre><p>Also, the PostgreSQL official documentation refers to these parameters as equal if your data fits your database memory.</p><pre>Tip<br><br>Although the system will let you set random_page_cost to less than seq_page_cost,it is not physically sensible to do so.<br>However, setting them equal makes sense if the database is entirely cached in RAM, since in that case there is no penalty for touching pages out of sequence. <br>Also, in a heavily-cached database you should lower both values relative to the CPU parameters, since the cost of fetching a page already in RAM is much smaller than it would normally be.<br><br>see: https://www.postgresql.org/docs/current/runtime-config-query.html#RUNTIME-CONFIG-QUERY-CONSTANTS</pre><ul><li><strong>Monitor Database Dead Rows and Vacuum Statistics</strong></li></ul><p>In PostgreSQL, it doesn’t immediately remove the old version of the row. PostgreSQL marks the old version as “dead” and creates a new version of the row. These dead rows take up space in the database but are no longer visible to any active transactions. Over time, dead rows accumulate and waste storage, causing performance degradation (because scans and indexes have to skip over them). PostgreSQL has an <strong>autovacuum daemon</strong> that runs automatically in the background to clean up dead rows regularly.</p><pre>SELECT<br>  schemaname,<br>  relname AS table_name,<br>  n_live_tup AS live_rows,<br>  n_dead_tup AS dead_rows,<br>  last_autovacuum,<br>  last_analyze,<br>  last_autoanalyze<br>FROM<br>  pg_stat_all_tables<br>WHERE<br>  n_dead_tup &gt; 0<br>ORDER BY<br>  n_dead_tup DESC</pre><p>In the above example, you can track and monitor each scheme and its dead row statistics to manage your optimal vacuum configuration to make. You can also update the vacuum setting in your postgresql.conf file or via the ALTER SYSTEM command. For more information on tuning and modifying, please visit the <a href="https://www.postgresql.org/docs/17/routine-vacuuming.html#VACUUM-BASICS">official documentation</a>.</p><p><strong>Tune PostgreSQL Settings:</strong></p><pre># Optional autovacuum tuning for better performance<br>autovacuum_vacuum_scale_factor = 0.05       # Lower threshold to trigger vacuum sooner<br>autovacuum_analyze_scale_factor = 0.02      # Same for analyze<br>autovacuum_vacuum_cost_delay = 10ms         # Shorter delay between vacuum steps<br>autovacuum_vacuum_cost_limit = 200          # More aggressive cleanup<br>autovacuum_max_workers = 5                  # Allow more workers in parallel</pre><ul><li><strong>PostgreSQL Plan Caching and Optimizations</strong></li></ul><p>In PostgreSQL, prepared statements are SQL queries with parameters that are planned once and reused. Their performance can vary depending on the parameter values, especially if the query involves joins or casts, since different values can lead to different optimal plans.</p><p>For example, if the first query used a very selective filter, the planner may choose an index scan. But if later the parameter value is not selective at all (e.g., returning many rows), the index scan might be the worst possible plan, and the planner won’t change it.</p><p>This feature can also be turned off or not enabled for some special queries, because it helps to minimize your plan time for overall operations.</p><p><strong>Tune Settings in PostgreSQL:</strong></p><pre>SET plan_cache_mode = force_generic_plan; # disable to use custom plans</pre><pre>// Dynamically build the query and use EXECUTE. This forces a fresh plan for each execution based on current parameters.<br>EXECUTE format(&#39;SELECT * FROM table WHERE col = %L&#39;, param); </pre><p>For more information on tuning and modifying, please visit the <a href="https://www.postgresql.org/docs/17/runtime-config-query.html#GUC-PLAN-CACHE-MODE">official documentation.</a></p><ul><li><strong>Monitor High I/O and Affected Data Space By Queries</strong></li></ul><p>In database systems, cascading operations (e.g., parent-to-child relationships) or unbounded query conditions can significantly impact I/O and increase overall system latency. If your monitoring tools or alerts fail to detect and track these operations, they may go unnoticed, ultimately affecting the system’s performance and violating your expected SLA metrics.</p><p>If you have the <a href="https://www.postgresql.org/docs/current/pgstatstatements.html">pg_stat_statements</a> extension enabled, this helps to monitor and alert to your long-running or IO-bound operations.</p><p><strong>Track These in PostgreSQL:</strong></p><pre>SELECT<br>  query,<br>  rows,<br>  calls,<br>  total_time,<br>  shared_blks_read,<br>  shared_blks_hit,<br>  blk_read_time,<br>  blk_write_time<br>FROM<br>  pg_stat_statements<br>ORDER BY<br>  blk_read_time DESC<br></pre><ul><li>shared_blks_read-&gt; blocks read from disk.</li><li>shared_blks_hit-&gt; blocks found in memory.</li><li>blk_read_time-&gt; time spent reading from disk.</li><li>blk_write_time-&gt; time spent writing to disk.</li></ul><p>It helps you when looking for queries with high shared_blks_read and high blk_read_time.</p><pre>SELECT<br>  relname AS table_name,<br>  heap_blks_read,<br>  heap_blks_hit,<br>  heap_blks_read * 8 / 1024 AS mb_read_from_disk,<br>  heap_blks_hit * 8 / 1024 AS mb_read_from_cache,<br>  ROUND(heap_blks_hit::numeric / NULLIF(heap_blks_hit + heap_blks_read, 0), 2) AS cache_hit_ratio<br>FROM<br>  pg_statio_user_tables<br>ORDER BY<br>  heap_blks_read DESC<br>LIMIT 10;</pre><p>This query helps to show which tables are causing the most disk reads. If data is being read from disk vs cache.</p><ul><li><strong>Conclusions</strong></li></ul><p>Query performance and its inconsistencies can depend on a variety of factors, including data characteristics and system behavior. However, overall performance is strongly influenced by how actively you maintain your data and stay aligned with the evolving needs of your application lifecycle. This post is based on my personal experience, and I welcome any feedback or suggestions you may have.</p><p>Thanks for your time, happy reading. Cheers 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6505c71972f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some Tips for Boosting Relational Database Performance in Software Development]]></title>
            <link>https://medium.com/@rohatsahin/some-tips-for-boosting-relational-database-performance-in-software-development-bd1069a6eba6?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd1069a6eba6</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 23:48:56 GMT</pubDate>
            <atom:updated>2024-08-11T01:06:27.723Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I will demonstrate how performance-oriented strategies in relational databases can enhance service efficiency during software development, ensuring that we uphold best practices and maintain full observability of our queries.</p><ul><li><strong>use CTE for repeating conditions in search operations</strong></li></ul><p><a href="https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL">Common Table Expression</a> (CTE) is a temporary result set you can reference within an SQL statement. CTEs are defined using the WITH clause and are useful for breaking down complex queries into simpler, more observable, and maintainable parts, enhancing observability and maintainability.</p><p>Some of the disadvantages:</p><p><strong>Performance Overhead</strong>: In some cases, CTEs can result in performance overhead because it might materialize the CTE result set (store it in memory) before executing the main query. This can slow down queries, especially if the CTE returns a large dataset.</p><p><strong>Limited Optimization</strong>: Because CTEs are often treated as isolated units, the query planner might not optimize them as effectively as inline subqueries or joins. This can sometimes lead to suboptimal execution plans.</p><pre>-- example of retrieve all catagories <br><br>WITH RECURSIVE CategoryCTE AS (<br>    SELECT id, name, parent_id<br>    FROM Category<br>    WHERE id = 1  -- Starting point (e.g., a specific category)<br><br>    UNION ALL<br><br>    SELECT c.id, c.name, c.parent_id<br>    FROM Category c<br>    INNER JOIN CategoryCTE cte ON c.parent_id = cte.id<br>)<br><br>SELECT * FROM CategoryCTE;</pre><ul><li><strong>design a cascading operation flow from descendants to ancestors.</strong></li></ul><p>A cascading operation in SQL refers to a set of actions automatically performed on related rows in a database when a specific action is executed on a parent row. These operations are typically associated with foreign key constraints, allowing the database to maintain referential integrity between tables.</p><pre>        // soft delete records by deletion order from descendants to ancestor, and prevent a large cascade of operations<br>        record.type.orderOfDeletion().forEach { type -&gt;<br>            var existRecords = true<br><br>            while (existRecords) {<br>                val itemIds = dsl.select(descendants.ID)<br>                    .from(descendants)<br>                    .where(descendants.TYPE.eq(type))<br>                    .limit(BATCH_SIZE)<br>                    .fetch(descendants.ID)<br><br>                existRecords = itemIds.isNotEmpty()<br><br>                if (existRecords) {<br>                    dsl.update(descendants)<br>                        .set(descendants.UPDATED_BY, userId)<br>                        .set(descendants.DELETED_AT, now)<br>                        .set(descendants.DELETED_BY, userId)<br>                        .where(descendants.ID.`in`(itemIds))<br>                        .execute()<br>                }<br>            }<br>        }</pre><p>In the above code snippet, the deletion process starts with the descendants and moves towards the ancestors. This approach helps prevent heavy database changes and minimizes their impact. It reduces the load on trigger executions and index modifications, leading to more efficient database operations.</p><p>Some of the practices:</p><p><strong>Avoid Deep Cascades</strong>: When deleting a large hierarchy, start with the child records rather than the parent. This approach helps avoid large transactions being duplicated and optimizes memory and I/O usage.</p><p><strong>Complex Queries</strong>: In cases where queries are complex and involve multiple tables, cascading operations can add to the complexity. Evaluate if partition and chuck handling might be more appropriate.</p><ul><li><strong>hierarchy table model stores ancestor-descendant relationships in a separate table.</strong></li></ul><p>These hierarchy tables are a database design pattern used to efficiently represent and query hierarchical or tree-like structures. This pattern helps manage parent-child relationships and allows for fast querying of ancestor-descendant relationships.</p><p>a principle of these hierarchy tables:</p><p><strong>Structure</strong>: The hierarchy table is a separate table that stores all possible ancestor-descendant relationships within the hierarchy.</p><p><strong>Representation</strong>: Each row in the hierarchy table represents a relationship between an ancestor and a descendant. It allows for quick retrieval of hierarchical paths.</p><p><strong>Flexibility</strong>: The hierarchy table supports various hierarchical queries, such as finding all descendants, ancestors, and paths between nodes.</p><pre>CREATE TABLE item_paths (<br>    ancestor_id,<br>    descendant_id,<br>    depth,  -- The distance between AncestorID and DescendantID<br>}<br><br>-- sample query<br><br>SELECT 1 AS one<br>FROM items AS ancestors<br>         INNER JOIN item_paths<br>                    ON item_paths.ancestor_id = ancestors.id<br>         INNER JOIN items AS descendants<br>                    ON descendants.id = item_paths.descendant_id</pre><ul><li><strong>use pagination for SQL operations and streaming actions</strong></li></ul><p>Pagination is a technique used to divide a large operation space set into smaller, more manageable chunks or pages. This is particularly useful for displaying large amounts of data in a user interface or when dealing with large mutation queries. SQL operations have their behavior for implementing pagination like as primary key or partition hash, but the core concepts are generally similar.</p><p>some of the practices:</p><p><strong>Use Indexed Columns</strong>: Always use an indexed column in the ORDER BY clause to improve performance. Pagination queries can be slow if they involve large data sets without proper indexing.</p><p><strong>Avoid Offset Base Pagination</strong>: Large offsets can lead to performance issues. Instead, consider alternatives like keyset pagination (also known as “seek method”), where you use the last retrieved record’s value as a reference for the next page.</p><pre>-- assuming the last ProductID from the previous page is 100<br>SELECT id, name<br>FROM Products<br>WHERE id &gt; 100<br>ORDER BY id LIMIT 10;</pre><ul><li><strong>adjust join types according to query conditions and data structure of tables.</strong></li></ul><p>SQL joins are fundamental for querying and combining data from multiple tables in a relational database, allowing for efficient retrieval of related information. For instance, when you only need matching data from both tables, an INNER JOIN is the most efficient choice. It reduces the dataset to only relevant matches, speeding up query execution, other hand your query logic requires retrieving all records from one or both tables, regardless of whether they have a corresponding match, use the appropriate outer join (LEFT, RIGHT, or FULL).</p><p>some of the practices:</p><p><strong>Data Distribution</strong>: Understand the distribution of data in your tables. If one table has significantly fewer rows than the other, consider placing it first in INNER JOIN, or using a LEFT JOIN if it’s the main table.</p><p><strong>Use Specific Conditions</strong>: Instead of joining on broad conditions, narrow your join conditions to specific columns and data types that best match your query’s purpose. For example, do not add more join conditions if it does not help reduce search space. This will cause more column-based scans and IO operations to be initiated.</p><p><strong>Index Join Columns</strong>: Ensure that columns used in join conditions are indexed. Indexes can dramatically speed up join operations by reducing the amount of data the database needs to scan.</p><ul><li><strong>ensure efficient normalization and index choices for query structures</strong></li></ul><p>Ensuring efficient normalization and index choices is crucial for optimizing query performance maintaining data integrity in a relational database, and making allies to foreign keys to enforce referential integrity and ensure that relationships between tables are maintained.</p><pre>-- assuming best way a index access method btre index<br>SELECT workspace_users.id, workspace_user_groups.id<br>FROM workspace_users<br>         INNER JOIN workspace_user_groups<br>                    ON workspace_user_groups.workspace_user_id = workspace_users.id<br>WHERE workspace_user_groups.group_id = 1;<br><br>-- assuming best way a index access method gist index<br>SELECT workspace_users.id, workspace_user_groups.id<br>FROM workspace_users<br>         INNER JOIN workspace_user_groups<br>                    ON workspace_user_groups.workspace_user_id = workspace_users.id<br>WHERE workspace_users.group_ids = ANY (CAST(&#39;{1}&#39; AS bigint[]));</pre><p>when the above two queries are examined, for the first one, the best choice would be a <a href="https://www.postgresql.org/docs/current/indexes-types.html#INDEXES-TYPES-BTREE">B-TREE</a> index, and for the second one, since it is an array operation, the best choice would be a <a href="https://www.postgresql.org/docs/current/indexes-types.html#INDEXES-TYPE-GIST">GIST</a> index.</p><p>some of the practices:</p><p><strong>Partial Indexes</strong>: In some databases like PostgreSQL, you can create partial indexes that only include rows meeting certain conditions. This can be useful for indexing only the subset of data that are frequently queried.</p><pre>-- Creating a partial index in PostgreSQL<br>CREATE INDEX idx_active_users ON Users(Id) WHERE IsActive = TRUE;</pre><p><strong>Covered Indexes</strong>: A covered index includes all the columns required by a query. This allows the database to retrieve data directly from the index without accessing the table, improving performance. This helps to make index-only scans instead of index scans.</p><p><strong>Column Order Important</strong>: The order of columns in a composite index affects its usefulness. Place the most selective column first, and ensure that the order matches how the columns are used in your queries.</p><p><strong>Avoid All Column Indexes</strong>: While indexes speed up data retrieval, they also slow down data modification operations (INSERT, UPDATE, DELETE) and consume additional storage. Only create indexes that provide a significant performance benefit.</p><p><strong>Foreign Key Columns</strong>: Index columns that are used as foreign keys. This helps speed up joins between related tables and improves referential integrity checks.</p><ul><li><strong>use table partitioning large and most frequently access tables</strong></li></ul><p>Table partitioning in SQL is a technique used to divide a large table into smaller, more manageable pieces, called partitions, based on specific criteria. Partitioning can improve query performance, simplify data management, and optimize storage.</p><p>In modern database systems, various partitioning strategies are available, and the choice of strategy depends on the specific SQL queries and physical requirements of your application. For example, you might choose between range, list, hash, or composite partitioning, depending on your data structure and how it is queried.</p><p>You can find detailed information about PostgreSQL</p><p><a href="https://www.postgresql.org/docs/current/ddl-partitioning.html">5.12. Table Partitioning</a></p><ul><li><strong>ensure select columns to be used and increase network efficiency</strong></li></ul><p>Select only the columns you need in your queries to minimize the amount of data transmitted over the network. Retrieving unnecessary data can increase network traffic and strain I/O resources, which may not automatically scale with demand. This practice is particularly effective for long-term pagination and concurrent transactions, as it helps maintain system scalability and ensures that your queries use less memory.</p><p>some of the practices:</p><p><strong>Avoid </strong><strong>SELECT *</strong>: Instead of selecting all columns, explicitly list the columns you need. This reduces the amount of data transferred over the network and speeds up query execution.</p><p><strong>Minimize Column Data Size</strong>: Ensure that columns have appropriate data types. For example, use VARCHAR(50) instead of TEXT if the data won&#39;t exceed 50 characters. This reduces the amount of data being transferred and stored.</p><ul><li><strong>ensure limits on the number of parameters in SQL queries</strong></li></ul><p>Simplified queries are faster and more efficient because they make better use of indexes and system resources. Fewer parameters contribute to greater readability and maintainability of queries. In contrast, queries with an excessive number of parameters can lead to resource fluctuations and unpredictable service responses, as these queries may fraction the system and create instability in the IO capacity. For example, when one query with thousands of parameters in a clause will create instability in monitoring the query.</p><p>If you are using <a href="https://www.jooq.org/">Jooq</a>, you can define a custom logger listener to track your slow queries and execution context, creating a useful context for warnings and alerts.</p><p><a href="https://blog.jooq.org/how-to-detect-slow-queries-with-jooq/">How to Detect Slow Queries with jOOQ</a></p><ul><li><strong>monitor database infrastructure and observe index and data operations with system metrics</strong></li></ul><p>Effective monitoring helps in identifying and addressing issues before they impact your applications. Here are some key practices for monitoring relational databases. As an example ideally, the number of rows fetched should be close to the number of rows returned (read/scanned) on the database. or the number of dead rows should not be steadily increasing over time, and, we must observe to continuously the number of sequential or index scans for checking operation performances.</p><p>For all these, database systems provide a system metric and actuator data, which an effective alerting structure and monitoring dashboards can be created.</p><p>As an example, datadog users can use this blog post for effective use of PostgreSQL monitoring.</p><p><a href="https://www.datadoghq.com/blog/aws-rds-postgresql-monitoring/#amazon-rds-postgresql-key-metrics">Key metrics for Amazon RDS PostgreSQL monitoring</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i259uYxOMnuFFvk9t0eyxA.png" /><figcaption>monitoring dashboard</figcaption></figure><p>You can access the configuration file for the monitoring dashboard that I created, and use it to set up and configure your own monitoring systems by importing <a href="https://gist.github.com/Rohatsahin/6e05cb21f6950179ac4379b264424325">this file</a>.</p><p><strong>Conclusions</strong></p><p>The performance must be dependent on whether you actively maintain your data and its relations to keep up to date with your developing lifecycle. This post has been created because of my past experiences and I am open to your feedback</p><p>Thanks for your time, happy reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd1069a6eba6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What could I do to ensure the maintainability of software projects]]></title>
            <link>https://medium.com/@rohatsahin/what-could-i-do-to-ensure-the-maintainability-of-software-projects-132dc13e4152?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/132dc13e4152</guid>
            <category><![CDATA[production-support]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[maintainability]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 08:37:26 GMT</pubDate>
            <atom:updated>2024-01-25T07:43:30.721Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, everyone. In this post, I will share some useful tips for improving the maintainability of software projects, a factor that is often overlooked during software development.</p><p>Most of the time, we label our software as legacy, potentially leading to significant refactoring and rewriting in the future. Although our business is not typically considered legacy or outdated, why is our software evaluated as such? This is because, while we align our business with future needs and dependencies, we often neglect the importance of maintaining and ensuring the quality of our software.</p><p>In the sections below, I will share the tips that I have taken care to implement in the software projects that run in the production environment created in recent years, based on my observations.</p><ul><li><strong>Dependency and Version Management</strong></li></ul><p>I rigorously manage third-party dependency versions and client libraries in all software projects, prioritizing their updates, monitoring their impact, and ensuring our software is adaptable to future needs.</p><p>The <a href="https://github.com/dependabot">Dependabot</a> has been a really good tool here. The release notes and version update notification pull requests (PRs) were very helpful in keeping track of and understanding changes.</p><p>Here are some benefits of using Dependabot in software projects:</p><ul><li><em>Security Updates</em>:</li></ul><p>The Dependabot regularly scans your project’s dependencies and notifies you of any security vulnerabilities in the libraries you are using. This proactive approach helps you address security issues promptly by updating to the latest, patched versions.</p><ul><li><em>Reduced Maintenance Overhead</em>:</li></ul><p>Keeping dependencies up-to-date is a crucial aspect of software maintenance. The Dependabot automates this process, reducing the manual effort required to monitor and update dependencies regularly.</p><ul><li><em>Visibility and Transparency</em>:</li></ul><p>The Dependabot provides clear and detailed information about the updates it proposes. This transparency allows developers to make informed decisions about whether to accept or reject specific updates based on their understanding of the changes.</p><ul><li><em>Enhanced Code Stability</em>:</li></ul><p>Regularly updating dependencies through Dependabot helps improve code stability by incorporating bug fixes and improvements from the latest versions of libraries.</p><ul><li><strong>Readme and Documentation</strong></li></ul><p>I am always trying to keep up to date with a project’s <a href="https://en.wikipedia.org/wiki/README">readme</a>. Software projects frequently entail numerous dependencies and resource usages, and these dependencies are subject to change in the future. As a result, the scope of responsibility may be extended or restricted, with their areas of application potentially evolving.</p><p>Here are some benefits of using Readme in software projects:</p><ul><li><em>Project Introduction</em>:</li></ul><p>The Readme provides an introduction to the project, explaining its purpose, goals, and scope. This helps newcomers quickly understand what the project is about.</p><ul><li><em>Configuration</em>:</li></ul><p>The Readme often covers configuration details, such as environment variables or specific settings, enabling users to customize the software to suit their needs.</p><ul><li><em>Project Structure</em>:</li></ul><p>Developers can gain insights into the project’s structure, file organization, and overall architecture through the Readme. This helps in navigating the codebase efficiently.</p><ul><li><em>Dependencies and Requirements</em>:</li></ul><p>It lists the dependencies and requirements for running the project. This information is crucial for developers to ensure that they have the necessary tools and libraries in place.</p><ul><li><em>Contributing Guidelines</em>:</li></ul><p>Many Readme files include guidelines for contributors, explaining how others can contribute to the project. This may cover topics like coding standards, pull request processes, and issue reporting.</p><ul><li><strong>Pull Request and Documentation Standards</strong></li></ul><p>I also ensure the creation of version control systems in the software project with a proper hierarchy, which is crucial for observing the software development process and establishing a healthy deployment flow. Therefore, I must ensure that the <a href="https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests">pull requests</a> we create are well-defined and include meaningful changes.</p><p>Here are some benefits of creating pull requests (PRs) in software projects:</p><ul><li><em>Each request pull request (PRs) must contain a single commit and all changes for successful deployment</em>:</li></ul><p>Simple and meaningful pull requests, such as those introducing new features, bug fixes, and system updates, will keep the Git history clear and facilitate easy rollback to address any issues.</p><ul><li><em>Well-detailed and addressed pull request (PRs) descriptions</em>:</li></ul><p>The description guides code reviewers. It helps reviewers understand the changes, making the review process more efficient and effective. A clear description allows reviewers to focus on specific aspects that may need attention.</p><p>For example, a small description <a href="https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/creating-a-pull-request-template-for-your-repository">template</a> like the one below will also help to achieve this.</p><pre>[link to task from tracing software]<br><br>[summary of what this PR does and why]<br><br>## Technical Changes<br><br>[List any major technical changes introduced in this PR, especially any breaking changes to existing code]<br><br>## Test Cases<br><br>[List the end-user workflows and edge cases to watch out for]<br><br>## Links and Screenshots<br><br>&lt;details&gt;<br>&lt;summary&gt;Click to expand&lt;/summary&gt;<br><br>[screenshots, videos, etc...]<br><br>&lt;/details&gt;</pre><ul><li><em>Avoid Large Pull Requests</em>:</li></ul><p>Large pull requests are harder to review. If possible, break down substantial changes into smaller, more manageable pieces. This helps in maintaining a smooth and efficient review process.</p><ul><li><strong>Code Linters and Formatters Standards</strong></li></ul><p>I try to use code <a href="https://github.com/typescript-eslint/typescript-eslint">linters</a> and <a href="https://github.com/prettier/prettier">formatters</a> are essential tools in software development for ensuring code quality, consistency, and maintainability. They contribute to a more efficient development process, faster collaboration among team members, and help produce reliable, readable code.</p><p>Here are some benefits of using linters and formatters in software projects:</p><ul><li><em>Consistency in Code Style</em>:</li></ul><p>Code formatters enforce a consistent coding style across the entire codebase. This is particularly crucial in projects with multiple developers, ensuring that the code looks uniform and is easier to read and understand.</p><ul><li><em>Reduced Merge Conflicts</em>:</li></ul><p>Code formatters help reduce these conflicts by ensuring that code changes are formatted consistently, facilitating smoother collaboration among team members.</p><ul><li><em>Enforcement of Coding Standards</em>:</li></ul><p>Code formatters can be configured to enforce specific coding standards and best practices. This ensures that developers follow established guidelines, leading to a higher level of code quality.</p><ul><li><em>Reduced Bugs and Issues</em>:</li></ul><p>Linters can catch common programming errors, such as syntax errors, undefined variables, or unused imports.</p><ul><li><em>Enforcement of Best Practices</em>:</li></ul><p>Linters can be configured to enforce best practices and coding standards. For example, preventing the use of <strong>any</strong> into TypeScript code and strengthening type definition.</p><ul><li><em>Automated Code Reviews</em>:</li></ul><p>Linters can be integrated into the code review process. This speeds up the review process and ensures that the code adheres to project standards before being merged.</p><ul><li><strong>Monitoring and Observability</strong></li></ul><p>I strive to adopt <a href="https://en.wikipedia.org/wiki/Observability_(software)">monitoring and observability</a> mechanisms that are essential for maintaining the health, performance, and reliability of software projects. A well-designed observability area can yield results that facilitate operations for developers and create a safe environment of trust for its changes.</p><p>Here are some benefits of monitoring and observability in software projects:</p><ul><li><em>Performance Optimization</em>:</li></ul><p>Monitoring and observability help developers optimize the performance of software by providing real-time data on various metrics. This allows for identifying and addressing performance bottlenecks, improving response times, and enhancing user experience.</p><ul><li><em>Early Issue Detection</em>:</li></ul><p>Monitoring allows for the early detection of issues and abnormalities in the software. This includes identifying errors, performance bottlenecks, and other issues before they impact users, enabling prompt resolution.</p><ul><li><em>Incident Response and Recovery</em>:</li></ul><p>In the event of incidents or failures, monitoring tools provide alerts and notifications. This allows teams to respond quickly, minimize downtime, and implement recovery strategies based on real-time data.</p><p>Also, I am linking a <a href="https://medium.com/@rohatsahin/thinking-about-observability-when-coding-565b0983735b">post</a> that I sharted before the points I attention to while continuous development.</p><ul><li><strong>Change and Depreciation Management</strong></li></ul><p>I pay attention to changes in the code used in production. Therefore, it is crucial to ensure the continuity of existing business requirements when managing changes and deprecations. For example, if a mandatory change is required in an API, it must encourage the <a href="https://www.postman.com/api-platform/api-versioning/">API version</a> and <a href="https://swagger.io/docs/specification/api-general-info/">documentation</a>. Also, another example of Java <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/javadoc/deprecation/deprecation.html">deprecation</a> is very useful for code migration. It will make it easier to manage migrations in code safety and smoothly.</p><p>Here are some benefits of change and depreciation management in software projects:</p><ul><li><em>Risk Mitigation</em>:</li></ul><p>Proper change management helps mitigate the risks associated with introducing modifications to the software. It involves thorough planning, testing, and validation, reducing the likelihood of introducing bugs or negatively impacting system stability.</p><ul><li><em>Deprecation Planning</em>:</li></ul><p>Depreciation management involves phasing out or discontinuing certain features, APIs, or components that are no longer needed or supported. Proper planning and communication are essential to guide users and developers through the deprecation process.</p><ul><li><em>Documentation and Communication</em>:</li></ul><p>Managing changes requires clear documentation and communication. This includes documenting the reasons for changes, providing release notes, and communicating effectively with stakeholders. Clear communication is vital for understanding the impact of changes and guiding users and developers through the transition.</p><ul><li><em>Business Agility</em>:</li></ul><p>Effective change and depreciation management enhance the overall agility of a software project. Teams can respond quickly to market changes, user feedback, and emerging technologies, ensuring that the software remains competitive and aligned with business objectives.</p><ul><li><strong>Code and Change Acceptance Testing</strong></li></ul><p>I ensure that every piece of code, when I set it to mainstream, is testable and includes testing. Code and acceptance testing are important for facilitating communication between developers and business teams, as well as managing the transition of progress. On the developer side, testing serves as a crucial tool for identifying and preventing bugs, as well as verifying business requirements. <a href="https://www.browserstack.com/live?utm_source=google&amp;utm_medium=cpc&amp;utm_platform=paidads&amp;utm_content=638521804522&amp;utm_campaign=Search-NB-Mix-Keywords-S1-US-EU&amp;utm_campaigncode=Web-App+1012782&amp;utm_term=b+web%20application%20testing%20tools&amp;gad_source=1&amp;gclid=Cj0KCQiAnrOtBhDIARIsAFsSe50hiGTmd_MC62y-7Dq0L38EdU2uMMxQAbvxggLMxxY_Xeh0YDaqQ5waAswaEALw_wcB">Acceptance testing</a> is vital for ensuring the success of development and providing business teams with visibility into performance criteria.</p><p>Here are some benefits of code and change acceptance testing in software projects:</p><ul><li><em>Error Detection and Prevention</em>:</li></ul><p>Testing helps identify errors, bugs, and issues early in the development process. This early detection prevents the propagation of defects into subsequent stages of development and, ultimately, into the production environment.</p><ul><li><em>Ensuring Code Quality</em>:</li></ul><p>Acceptance testing ensures that the code meets predefined quality standards and follows coding conventions. This contributes to the overall quality of the software, making it easier to maintain and reducing the likelihood of future defects.</p><ul><li><em>Change Impact Assessment</em>:</li></ul><p>Testing allows teams to assess the impact of the changes on the existing system. This helps in understanding potential dependencies, ensuring that modifications do not introduce unintended consequences.</p><ul><li><strong>Conclusion</strong></li></ul><p>I believe that software development follows a life cycle. Therefore, I consider it important to establish a productive and healthy environment to foster positive outcomes. A question I frequently encounter is, ‘When does a software project become legacy?’ The answer is often found in software projects that have been neglected or not maintained over time. Even when software projects undergo refactoring or re-platforming, expectations often remain unchanged at the end of the day.</p><p>Thank you for reading. 😊 I will be grateful for your opinion and contributions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=132dc13e4152" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Learned Using NoSQL Database in Projects]]></title>
            <link>https://medium.com/@rohatsahin/what-i-learned-using-nosql-databases-in-projects-4058e1cea857?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4058e1cea857</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[nosql]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Tue, 04 Oct 2022 09:01:22 GMT</pubDate>
            <atom:updated>2022-10-04T09:23:11.151Z</atom:updated>
            <content:encoded><![CDATA[<p>This post will discuss my learning and some tips for working with NoSQL databases. These recommendations are to improve our system reliability and maintainability in the future.</p><ul><li><strong>avoid excessively large document size</strong></li></ul><p>The large documents slow down entire network traffic so it’s the same as a tree stump into the river. If we do not prevent this problem, we may encounter many anomalies in our systems. For example, application side P99 response times are unpredictable, or one database node is take much more network traffic than others. The best option is if you have large documents in the system stop moving into your entire infrastructure or eliminate these document movements to your most recently used network.</p><ul><li><strong>avoid stale documents in database memory</strong></li></ul><p>The power of NoSQL databases all data operations occurring in memory and serving this data memory first. When the data size is growing in databases, it’s using the ejection policies and adding new ones to the memory to keep up the performance gains, so always having the most recent data is important for performance and resource consumption. İf we hold the most recent data, it helps us reduce recovery time and cost savings by hardware utilization.</p><ul><li><strong>avoid default and null values stored in documents</strong></li></ul><p>Default, null values, or keys in the documents increase document memory size, also if we use backup or replication this dramatically increases our data to the overall architecture. These values are most of the time used for your data model deserialization, so don’t store empty arrays or null values in databases, it also helps your code be clear 😁 and avoid invisibilities.</p><ul><li><strong>don’t fetch unused data and increase network efficiency</strong></li></ul><p>When we create our read model and avoid the fetch of unused or unnecessary values in our database request this eventually increases our performance metrics and creates efficient network traffic. because IO resources many time doesn’t auto-scalable and it creates the bottom lack of your system scalability. so if we make our request more reliable and useful, this situation will allow us to get more traffic and downgrade our resource usage.</p><ul><li><strong>use optimistic lock (versioning) and eliminate concurrency issues</strong></li></ul><p>The NoSQL database is very efficient for writing performance because these databases make all their changes as appending to the existing data and compact these changes after reaching a defined threshold value, so this performance maybe brings us some consistency troubles. We could have many concurrency problems with working with these databases, so we must create our changes with the version, and when a conflict happens, try again. Couchbase can use <a href="https://docs.couchbase.com/java-sdk/current/howtos/concurrent-document-mutations.html">CAS</a> for this issue. and it throws an exception for notifying the client side. more detail is <a href="https://en.wikipedia.org/wiki/Optimistic_concurrency_control">here</a>.</p><ul><li><strong>avoid multi-document mutation in your saving request</strong></li></ul><p>The NoSQL databases aren’t ACID familiar systems, so if we do multi mutation but this mutation affects many documents, the operation isn’t guaranteed with success or failure result. If our business drives this situation for us, try some distributed transaction patterns. For example <a href="https://learn.microsoft.com/en-us/azure/architecture/reference-architectures/saga/saga">SAGA</a> or some orchestrator for managing this transaction.</p><ul><li><strong>manage timeout and process retries by your service SLA’s</strong></li></ul><p>Timeouts and retries are determines our behavior and responses to the operations and results expected in our systems. so if we aren’t predicting our thresholds these values badly affect our performances. Timeouts are responding for our future when something is going wrong, and these values are important to define with P50 and P95 metrics with efficient values, also retries increase our availabilities. For example, if three times after retry wasn’t returned expected value switch to read replica may be a good approach to increase the availability.</p><ul><li><strong>manage replication factor and consistency level by your SLA’s</strong></li></ul><p>The network and infrastructure aren’t the consistent all time. and this makes it important you define your replication factor and consistency level for preventing data loss and increasing service operation time. For example, if your database setup has three regions then you maybe set two replicas for the master data to increase your availability. Moreover, databases use async replication between the clusters, so consistency level is important if your data is critical or not. For example, if you have a payment system should use sync replication between clusters as more feasible for avoiding consistency issues between nodes when the failover will happen.</p><p><strong>Conclusions</strong></p><p>The NoSQL databases are very feasible for high write and fast operations, but this performance must dependent on if you actively maintain your data and keep up to date with your developing lifecycle. This post has been created my past experiences and I am open to your feedback</p><p>Thanks for your time, happy reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4058e1cea857" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Outbox Pattern Implementation on Couchbase DB]]></title>
            <link>https://medium.com/trendyol-tech/outbox-pattern-implementation-on-couchbase-db-c640ac21bcd5?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c640ac21bcd5</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[couchbase]]></category>
            <category><![CDATA[reliability]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Tue, 12 Apr 2022 09:08:52 GMT</pubDate>
            <atom:updated>2022-04-12T09:08:52.730Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, In this article, we introduce how to implement an outbox pattern to couchbase and deliver your messages more reliable.</p><p>Outbox pattern is mostly applied when our system generates changes by its domain and we use it when our changes require a delivery guarantee for external systems, for example (messaging systems, or async callbacks).</p><p><strong>Implementation in Couchbase</strong></p><p>After a piece of quick information about the goal of the outbox pattern. We are starting to inform about the infrastructure that powers the solution and the solution and the parts that make up the solution. Finally, we will complete by giving the pros and cons.</p><p><strong>Couchbase Eventing</strong></p><p><a href="https://docs.couchbase.com/server/current/eventing/eventing-overview.html">Eventing</a> is a service of Couchbase like other services to data or indexing, and it’s responsible for tracking document changes. Our solution is empowered by the Eventing Service. It captures changes in our business model and saves them to the outbox bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rmfEfn_fGUqzQmcaarmbg.png" /><figcaption>overall architecture</figcaption></figure><p>The business bucket is to store your information, it should also store the event of that change if any change occurs because most NoSQL systems do not have acid processing but document level changes bring consistency and this is a simple transaction boundary.</p><p>For example, Our business bucket is storing stock data and it has stock quantity and also includes events if any changes have occurred.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/982ba84cf34239323fd3e3f2dc000275/href">https://medium.com/media/982ba84cf34239323fd3e3f2dc000275/href</a></iframe><p>When the business model is successfully updated and the changes in the event are created, the eventing service catches this change and records it to the outbox bucket with success.</p><p>This process is managed by the eventing service and, its eventing <a href="https://docs.couchbase.com/server/current/eventing/eventing-Terminologies.html#eventing-function">function</a> is a collection of JavaScript functions together react to a class of events. This javascript function was created by us for our business needs.</p><p>The function required for our solution is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d75ea27801b3008089181ded06c2f0f8/href">https://medium.com/media/d75ea27801b3008089181ded06c2f0f8/href</a></iframe><p>The function is running after our business document is changed and mutation is successfully created. The twelfth line of code is referring to your outbox bucket where the events are stored. The seventh line of code is referring to our business document events that are created after changed occurred.</p><p>Other service-specific terminologies are available in this <a href="https://docs.couchbase.com/server/current/eventing/eventing-Terminologies.html">document</a>.</p><p>After, we create and store our changes now require to publish or notify required systems. Our challenge was the need to publish to Kafka, now that we have fully saved the changes.</p><p><strong>Couchbase Kafka Connector</strong></p><p>Couchbase, have several connectors to send changes to other systems. For example, <a href="https://docs.couchbase.com/kafka-connector/current/quickstart.html">Kafka</a>, <a href="https://docs.couchbase.com/elasticsearch-connector/current/index.html">Elasticsearch</a>, etc. Kafka connector is the second part of our outbox solution. It’s delivering our stored messages with at least one delivery to Kafka. The connector is sporting extensibility and you also modify your delivery requirements, more detail and a setup guide are <a href="https://docs.couchbase.com/kafka-connector/current/source-configuration-options.html">here</a>.</p><p><strong>Observability</strong></p><p>Observability is also the main requirement of this solution because if message delivery time is increased or any long-running incident is not handled in the system tolerated time, consistency issues are occurring and invalid decisions are created by message consuming systems. Couchbase Server comes with Prometheus exporter, so it’s exposed system metrics and you are able to create your alerts. For example, outbox bucket filling up alert, and eventing processing error threshold alert are some examples of server-side alerts.</p><p>The Kafka Connector also has a rest API for its application runtime alert for example you create a stream queue alert or Kafka publishes rate alerts are some examples of connector side alerts.</p><p><strong>Pros and Cons</strong></p><p>This architecture had some pros and cons when we started building it, so we worked on the cons and provided more realistic observability and performance contributions to our SLA metrics.</p><p>Example of Pros</p><ul><li>We prevented message loss and increased the system consistency rate.</li><li>Business application is independent of message infrastructure and the availability rate is increased.</li><li>We have more control over application messages, so back pressure is more controllable.</li></ul><p>Example of Cons</p><ul><li>Couchbase Kafka Connector doesn’t expose much more metrics for our SLA requirements, so we forked the connector project and implement our observability stack components.</li></ul><p><strong>Conclusion</strong></p><p>Modern microservice architectures most of the time focus on stability and availability, but consistency is another part of reliable systems. In this article, we have described one of the ways, when we use the couchbase our database system and ensure consistency in our microservice systems.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c640ac21bcd5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trendyol-tech/outbox-pattern-implementation-on-couchbase-db-c640ac21bcd5">Outbox Pattern Implementation on Couchbase DB</a> was originally published in <a href="https://medium.com/trendyol-tech">Trendyol Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Purchasable Car Finding Crawler to Making Time Cost Discounting]]></title>
            <link>https://medium.com/@rohatsahin/easiest-car-finding-crawler-to-making-time-cost-discounting-9770fb809e24?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9770fb809e24</guid>
            <category><![CDATA[crawling]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 18:45:47 GMT</pubDate>
            <atom:updated>2022-03-22T20:59:54.324Z</atom:updated>
            <content:encoded><![CDATA[<p>Buying a car in Turkey has always been an extremely expensive act, but in recent years finding a car to buy has become more difficult than buying it. 😊</p><p>As we all know, it’s not a big deal to buy a car in any country, but in Turkey’s it’s also a very big deal to find a car. I am a software developer, and sometimes I like to do new things as a hobby that will make my time easier and also keep my curiosity alive.</p><p>In this post, I will describe my crawler application that will be coding with javascript and powered by AWS resources.</p><p>Before I start, I wanted to show the overall arch with the diagram below. Here, I aimed to trigger a lambda function at some intervals and find a car that can be ready for sale from the source site, and report it to me via Slack.</p><figure><img alt="sample diagram to business flow" src="https://cdn-images-1.medium.com/max/1024/1*cjn7tA1Eb8OYUMwkVTHZwA.png" /><figcaption>sample diagram to business flow</figcaption></figure><p>Amazon EventBridge is sent a <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html">CloudWatch</a> event to trigger a lambda function and the lambda function gets data from the official website and processes this data. if any available car data hits after the process, I am notified and I start phone calls to buy and use my time efficiently.</p><p>End of this post, I have shared lambda code to <a href="https://github.com/Rohatsahin/polo-reporter-bot">my github page</a>. Last summer, my car buying process really annoyed me, but I made it fun with things, and I wanted to explain one of the things with this post.</p><p>Thank you for reading.</p><p>Cheers!.</p><p>🍻</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*BA6M2QDj2tDv1x0fEoAfcw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9770fb809e24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Covid-19 Aşılanma Yüzdesini Gösteren Twitter Botu Geliştirmek]]></title>
            <link>https://medium.com/@rohatsahin/covid-19-a%C5%9F%C4%B1lanma-y%C3%BCzdesini-g%C3%B6steren-twitter-botu-geli%C5%9Ftirmek-28eb5d1a57bf?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/28eb5d1a57bf</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 17:50:35 GMT</pubDate>
            <atom:updated>2022-04-15T10:50:36.972Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Öncelikle yaşadığımız global pandemi koşullarında yaşamını yitiren tüm sevdiklerimizi saygı ile anıyoruz.</em></p><p>Bu yazımda Covid-19 aşılanma yüzdelerini günlük olarak hesaplayıp elde ettiğimiz sonuçları Twitter ile bir post oluşturup yayınlamayı sağlayan uygulamayı anlatacağım.</p><p>Biz yazılımcılar çoğu zaman hobi olarakta yada kendi zevk ve ihtiyaçlarımızı için yazılımlar geliştirebiliriz. Bende salgından kurtulmak yada kontrol altına alınması için bilim insanlarının geliştirdiği çözüm olan aşı için toplum içinde uygulanma yüzdesi ve toplumsal bağışıklığı Türkiye özelinde için gösteren bir Twitter botu geliştirmeyi anlatacağım. Bu fikir birgün mesai sonrası bir gezide bankta otururken aklıma geldi 😀 ,bunuda küçük bir anekdot olarak belirtiyim.</p><p>Öncelikle aşağıda uygulamanın nasıl bir mimari akışı olduğunu belirten diagram ile başlayalım bu bize küçük bir izlenim kazandıracaktır. Sonrasında detayları olarak bu akıştaki noktalara değineceğim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1-B_rU6uzvB5sreX04_Sw.png" /><figcaption>simple application architecture</figcaption></figure><p>Yukarıda genel olarak belirtiğim diagramda uygulamamız aws üzerinde kurulu olmakta ve her gün saat 18:00 da event bridge üzerinde zamanladığımız event ile lambda fonksiyonumuz tetiklenerek Covid-19 aşılanma yüzdelerini ve etkili bağışıklık oranı bilgilerini sağlık bakanlığının web sayfası üzerinden alarak Twitter daki <a href="https://twitter.com/CountVaccine?s=20"><strong>Turkey Vaccine Tracker</strong></a><strong> </strong>profili üzerinde tweet ile bilgilendirmesini yapıp akışını tanımlamaktadır.</p><p>Diagramdaki data soruce olarak sağlık bakanlığının Covid-19 aşı ve istaiklerini paylaştığı <a href="https://covid19asi.saglik.gov.tr/">web sayfasını</a> kullandım. Burada il bazında ve ülke genelindeki aşılanma bilğilerine erişebildim. Lambda fonksiyonu bu safyayı scrap ederek tweet oluşturmak için ihtiyaç duyduğu verilere erişmektedir.</p><p>Lambda fonksiyonunun her gün aynı önceden belirlediğim bir zamanda çalışmasını sağlamak için ise aws’nin event bridge servisini kullandım, burda bir cron expresion oluşturarak her gün 18:00 da çalışmasını amaçladım.</p><p>Aşılanma yüzdesi ve bağışıklık oranı gibi önemli verilerimizi oluşturup tweet olarak iletme görevini ise aws nin lambda servisi üzerinde koşan bir javascript uygulaması ile geliştirdim. Burada sağlık bakanlığının web sayfası üzerinden verileri alıp ardından ilgili veri seti ile Twiter da post oluşturmak için lamda üzerinde koşan kod parçası ise aşagıdaki gibidir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65abfc6d3e4bf5b1bec6b5f2e2ed6c3b/href">https://medium.com/media/65abfc6d3e4bf5b1bec6b5f2e2ed6c3b/href</a></iframe><p>Aws ye deploy ettiğim lambda projesinin koduna <a href="https://github.com/Rohatsahin/turkey-vaccine-tracker-bot">buradan</a> ulaşabilirsiniz.</p><p>Twitter üzerinden botun sayfasına <a href="https://twitter.com/CountVaccine?s=20">buradan</a> ulaşabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*owPeO6PGOZukyjx4tS0M1Q.png" /><figcaption>Twitter account main page</figcaption></figure><p>Umarım faydalı bir yazı olmuştur. Zaman ayırıp okuduğunuz için teşekkür ederim. 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28eb5d1a57bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking about Observability when Coding]]></title>
            <link>https://medium.com/@rohatsahin/thinking-about-observability-when-coding-565b0983735b?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/565b0983735b</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[alerting]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 13:43:48 GMT</pubDate>
            <atom:updated>2021-03-20T13:43:48.683Z</atom:updated>
            <content:encoded><![CDATA[<p>The fact that the modern systems we develop are consistent, scalable, and reliable is usually one of the main priorities of our software development processes.</p><p>In this context, we follow some development practices while coding our applications, for example, we have test-driven development and if the tests are successful, we assume that the application works as expected.</p><p>If so, can observability be one of the software development processes? Should we evaluate the following questions that we seek answers for most of the time as part of our software development processes and evaluate their solutions within our processes?</p><p>Where does the latency occur?<br>Which hop takes the most processing time?</p><p>In this article, we will show you the observability issues when we encounter while developing software.</p><ul><li>observability to detect latency</li></ul><p>Asynchronous programming is very popular in these days software development practices, but it brings some difficulties with it. For example, If we switch context at some points inside our code, It can cause logging and tracking issues and can be more difficult to manage than synchronous programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILhwku9NzV8Z1hvbX0ZXSA.png" /><figcaption>if attention is not paid to change context switching</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dRCZ2ARndGt-HByRI9ALw.png" /><figcaption>if attention is paid to change context switching</figcaption></figure><p>In the example charts above, since we could not see the part that caused latency after development, we first worked on seeing the problem instead of solving it, and in this way, it saved us a lot of effort to identify the problem, and it also showed that we can solve in a short time.</p><ul><li>observability to scalability</li></ul><p>We can define scalability as the ability to remain healthy in unexpected traffic movements in our software systems and modern deployment systems for example Kubernetes offer autoscale configurations for these unexpected moments.</p><p>However, for autoscaling our applications need to respond to these behaviors, for example, we should have a short startup time but sometimes we may not have such a feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yjpaye1n7vvjjt_gbE6Y7w.png" /><figcaption>web transaction time chart when unexpected traffic received</figcaption></figure><p>When we first encountered the above chart example, we thought that a part in the system did not work as expected, but the situation we encountered in our detailed examinations was that we encountered unexpected traffic due to too many transactions in a short time period.</p><p>We could follow the CPU and memory measurements and create an automatic scale configuration, but the system’s warm-up time may not be enough sufficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9A1hi7GgFEACWi3NDe2GA.png" /><figcaption>grafana dashboard to future operations</figcaption></figure><p>Could we have predicted this situation using the data? The answer to this question was yes for us, then we created a metric table and monitored our data, after data above our thresholds we determined, created alarms, and planned our scale.</p><ul><li>observability to availability</li></ul><p>Availability means that a system is operational at a given time, although we prioritize accessibility when designing our systems and we can prevent collective crashes, problems with accessibility can critically impact the state of our data.</p><p>For example, with a problem in our inventory system, users were adversely affected and the error rate increased in other systems, creating unexpected problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTVnzhNYoB01YbtGdBF2JA.png" /><figcaption>transaction count chart</figcaption></figure><p>After the problem we experienced, we analyzed our critical codes in the system, created trackers for their transactions, generated system warnings in case of errors, and increased our availability percentage by minimizing the problem.</p><ul><li>observability to debugging</li></ul><p>In modern systems, a request can proceed through many application code subroutine or other software systems, and the common approach about debugging is figuring out where the unpredictable code lives on your system.</p><p>In this unpredictable, we aim to consider our requests as a context and to examine the subroutine of the context and their visibility within themselves. For example, the <a href="http://logback.qos.ch/manual/mdc.html">MDC</a> we use in our java developments or the tools use in modern distributed systems such as <a href="https://www.jaegertracing.io/">Jaeger</a> and <a href="https://zipkin.io/">Zipkin</a> are based on the concept of creating a context for observability.</p><p><strong>Conclusion</strong></p><p>When we use programming techniques or design models in our application development processes, we aim to make our code more readable for humans and ensure maintainability in our systems.</p><p>Observability is the readability of our systems at runtime, in this way, we make it easier to detect malfunctions in our systems and increase their durability for unexpected situations.</p><p>Thank you for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=565b0983735b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Couchbase kullanılan projelerde zamanlanmış (schedule) görevler oluşturmak]]></title>
            <link>https://medium.com/trendyol-tech/couchbase-kullan%C4%B1lan-projelerde-zamanlanm%C4%B1%C5%9F-schedule-g%C3%B6revler-olu%C5%9Fturmak-134d1cdee700?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/134d1cdee700</guid>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[couchbase]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Thu, 28 May 2020 14:13:40 GMT</pubDate>
            <atom:updated>2020-05-28T15:16:43.940Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba. Bu yazımızda Couchbase kullanacağımız projelerde zamanlanmış görevlerimizi nasıl oluşturabileceğimiz örneklendirip, kullanabileceğimiz yerleri ve kazanımlarımızı anlatacağız.</p><p>Öncelikle zamanlanmış görev (schedule task) ile üzerinde duracağımız kavramdan bahsedecek olursak, belirli zaman aralığında çalıştıktan sonra bitiş zamanın gelmesi ile sona ermesini beklediğimiz ya da belirli koşulları saglamış ve başlangıç zamanının gelmesi ile statüsünü değiştirip aktif olacak datamız olarak özetleyebiliriz. Bir ürünü belirli zaman aralıklarında satıştan çekme, açma yada onaylanmış bir kampanyanın başlangıç tarihi geldiği zaman satışta statüsüne geçmesini örnek gösterebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*foBJLwMQOcbLc_unyxzvXA.png" /></figure><p>Couchbase ise nosql bir veritabanı çözümü ve data üzerindeki gerçekleşen işlemlerini kendi içinde özelleşen <a href="https://docs.couchbase.com/server/6.5/learn/architecture-overview.html">servisleri</a> ile yönettiği bir yapıya sahip. Yazımızda bize yardım edecek olan ise e<a href="https://docs.couchbase.com/server/6.5/eventing/eventing-overview.html">venting</a> servisi olacak. Eventing ile datamızda gerçekleşecek değişimleri izleyip yönetebileceğiz ve sunmuş olduğu özellikleri ile zamanlanmış görevlerimizi oluşturacağız.</p><p>Girişimizi gerçekleştirdiğimize göre bir örnek ile nasıl bir yol izleyeceğimizi açıklayabiliriz. Örneğimiz de onay statüsünde olan ve başlangıç tarihi geldiği zaman aktif olmasını istediğimiz bir kampanyayı nasıl aktifleştireceğimizi anlatacağız.</p><p>Öncelikle zamanlanmış görev ile bu işi nasıl yaptığımızı örnekleyelim. Elimizde onaylandı statüsünde bir kampanya datası var ve önümüzdeki zaman içerisindeki bir anda iptal edilmediği sürece başlangıç tarihi geldiği anda aktifleşmesini istiyoruz, bunu koda döker ise aşağıdaki gibi bir şey bizim için çözüm olabilecektir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c397ac3536556d5189a8c656e75428e2/href">https://medium.com/media/c397ac3536556d5189a8c656e75428e2/href</a></iframe><p>Örnek kod parçası inceleyecek olursak, beş dakika aralıklarla çalışıp veritabanından onaylı statüsünde olan kampanyaları çekip başlangıç tarihine ulaşanları aktive etmekte. Uygulamamızın birden fazla ortamda çalışması nedeniyle oluşması muhtemel race condition’ların önüne geçmek için de distributed bir lock (withLock) ile birlikte çalışmaktadır.</p><p>Couchbase ile bu süreci oluşturmak istediğimizde ise <a href="https://docs.couchbase.com/server/6.5/eventing/eventing-overview.html">eventing service</a>’nin bize saglamış olduğu fonksiyon özelliklerinden yararlanacağız. Couchbase eventing fonksiyonları data üzerinde geçekleşen crud veya expiry operasyonları sonrasında javascript ile yazdığımız ve couchbase eventing platformu üzerinde çalışan kod parçacıklarımız olarak tanımlayabiliriz. Bir bakıma serverless yapılar ile benzerlik göstermekte.</p><p>Tanımlayacağımız fonksiyon ile kampanya datası üzerindeki değişimleri takip edip kampanya statüsü onaylandığı anda kampanyanın başlangıç zamanını referans alan bir <a href="https://docs.couchbase.com/server/6.5/eventing/eventing-timers.html">timer</a> yaratacağız. Oluşturduğumuz timer fonksiyonu çalışma zamanına ulaştığı anda ilgili kampanya için gerekli olan servisine <a href="https://docs.couchbase.com/server/6.5/eventing/eventing-curl-spec.html">curl</a> ile http isteği yapıp kampanya statüsünü aktifleştirecektir. Bunu gerçekleştirmek için yazacağımız fonksiyonun örneği ise aşağıdaki gibi olacaktır.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f137200c89e948501c91ca0ee2224239/href">https://medium.com/media/f137200c89e948501c91ca0ee2224239/href</a></iframe><p>Yazdığımız fonksiyonu inceleyecek olursak, <strong>OnUpdate(doc, meta)</strong> fonksiyonu data üzerindeki her değişimde eventing servisi tarafından çalıştırılacak method olacaktır, ardından approved statüsüne ulaşan kampanyalar için ise eventing servisinin sağlamış olduğu <a href="https://docs.couchbase.com/server/6.5/eventing/eventing-timers.html">timer</a> özeliğini kullanarak <strong>createTimer</strong> fonksiyonu ile kampanya başlangıç zamanını referans alan bir event yaratacağız. Eventimizi yaratırken ki verdiğimiz <strong>onSaleTimer</strong> isimli callback fonksiyonumuz ile timer fonksiyonumuz çalışma zamanına ulaştığı anda eventing servisi tarafından sağlanan <a href="https://docs.couchbase.com/server/6.5/eventing/eventing-curl-spec.html">cUrl</a> fonksiyonu ile external servisimize kampanya datamızı bildirerek satışa açma işlemlerinin başlamasını sağlayacağız. Burada ki <strong>source_bucket</strong> ve <strong>apiUrl</strong> olarak kullandığımız değişkenler ise fonksiyon deployment işlemi sırasında verdiğimiz ortam spesifik değişkenleriniz olacaktır.</p><p>Deployment adımlarını ve örnek fonksiyonlar için <a href="https://docs.couchbase.com/server/6.5/eventing/eventing-examples.html">buradaki</a> dökümanlar üzerinden ilerleyerek sizlerde kendi fonksiyonlarınızı oluşturabilirsiniz.</p><p>Zamanlanmış görevlerimizi couchbase eventing fonksiyonlarına çevirdikten sonra kazanımlarımızın üzerinden ilerleyerek neden yaptığımızı açıklamak istersek:</p><ul><li>Zamanlanmış görevlerimizi scale etmiş olduk. Tüm kampanyaların aynı saate başlayacağı bir durumda tek ortam üzerinde çalışan job yavaşlayabilir yada çok fazla data üzerinde işlem yapmamız halinde öngöremediğimiz kaynak sıkıntıları (bellek, cpu) ile karşılaşacağımız için işlemlerimiz gecikebilir yada hatalar oluşabilir.</li><li>Belirli zaman aralığında çalışmasını istediğimiz (bir ürün 2 gün yayında kalsın gibi) görevlerimiz için bir ara statü oluşturma gereksinimini ortadan kaldırıp (on going gibi) kod karmaşıklığımızı azaltmış olduk.</li></ul><p>Son olarak kullanabileceğimiz başka durumlar için örnek verecek olursak:</p><ul><li>Arşivlenmesini istediğimiz aktif olmayan datalarımız için fonksiyonlar oluşturabiliriz. (kapanışı üzerinden 15 gün geçmiş)</li><li>Datalarımızı zenginleştirebiliriz.(döküman yaratıldıktan sonra başka servislere bağımlı datalarımızı alabiliriz. (data enrichment)</li><li>Data değişimleri sonucunda gerekli olan sistemlere yada başka data kaynaklarına bildirimler gönderebiliriz.</li></ul><p>ve aklımıza gelebilecek daha fazlası…</p><p>Umarım faydalı bir yazı olmuştur. Okuduğunuz için teşekkürler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=134d1cdee700" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trendyol-tech/couchbase-kullan%C4%B1lan-projelerde-zamanlanm%C4%B1%C5%9F-schedule-g%C3%B6revler-olu%C5%9Fturmak-134d1cdee700">Couchbase kullanılan projelerde zamanlanmış (schedule) görevler oluşturmak</a> was originally published in <a href="https://medium.com/trendyol-tech">Trendyol Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micrometer ile Prometheus Metrikleri Oluşturma]]></title>
            <link>https://medium.com/trendyol-tech/micrometer-ile-prometheus-metrikleri-olu%C5%9Fturma-808abde7fda3?source=rss-928849028fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/808abde7fda3</guid>
            <category><![CDATA[micrometer]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Rohat Şahin]]></dc:creator>
            <pubDate>Wed, 20 May 2020 10:58:36 GMT</pubDate>
            <atom:updated>2020-05-20T10:58:36.924Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba. Bu yazıda <a href="https://prometheus.io/">prometheus</a> ve <a href="https://micrometer.io/">micrometer</a> kullanarak nasıl metrikler oluşturacağımızı ve bunların kullanım alanları ile ilgili küçük bilgiler vereceğim.</p><p>Öncelikle prometheus ve micrometer hakkında küçük bilgiler vererek başlayalım. Prometheus geliştirdiğimiz uygulamarı ya da rabbitMQ, SQL server ve daha birçok infrastructure sistemlerimizi <a href="https://prometheus.io/docs/instrumenting/exporters/">exporter</a> libraries ile entegre edip sistem metriklerini gözlemleyebileceğimiz veya alert tanımlamaları yapabileceğimiz bir monitoring çözümüdür.</p><p>Micrometer ise java uygulamalarımız için çalışma zamanındaki veya kendi oluşturabileceğimiz metrikleri prometheus, newrelic vb monitoring sistemlerine aktarabileceğimiz formata dönüştüren bir client olarak tanımlayabiliriz.</p><p>Yazımızda ilerleyeceğimiz örnek uygulama aşağıda paylaşmış olduğum diagramdaki gibi olacak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYSMl8gtdSfDVzd8PjTyrg.png" /></figure><p>Sql server veya elasticsearch’dan topladığımız datalarımızı metic collector uygulamamızda micrometer yardımı ile prometheus serverimizi besleyeceğimiz formata çevireceğiz ve grafana ile prometheus’u datasource olarak kullanıp datamızı görselleştireceğiz.</p><p>Kısaca bunu yapma amacımızın üzerinden geçecek olursak Trendyol’da pim ekibi olarak kampanya ve satışa sunulan içeriklerin oluşturulması ve yönetilmesinden sorumlu olan takımız. Business ekibimizden gelen ihtiyaç doğrultusunda, satışta olan kampanyaları görebilecekleri ve pim kullanıcılarının süreçlerini takip edebilecekleri ekranları tasarlamaya başladık.</p><p>Burada açıklayacağımız örnek üzerinde “Önümüzdeki yirmi dört saatte kaç adet kampanya açılacak” sorusuna yanıt bulacağız.</p><ul><li>Metrics collector uygulamamızda elasticseach’e bağlanıp oluşturduğumuz seach query ile o an için yirmi dört saat içinde açılacak kampanyalarımızı bulacağız, örnek kod parçacığımız aşağıdaki gibi olacak</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f8f8f090e96d2c6994b3dffefa0af7c/href">https://medium.com/media/7f8f8f090e96d2c6994b3dffefa0af7c/href</a></iframe><ul><li>Datamızı oluşturduktan sonra micrometer yardımı ile prometheus’u besleyeceğimiz data formatını oluşturabiliriz. Micrometer burada bize <strong>MeterBinder</strong> arayüzünü sağlıyor. Bunun ile kendi özelleştirdiğimiz metriklerimizi tanımlayacağız, örnek kod parçacığımız aşağıdaki gibi olacak</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b405d6ff9649ac7ebf627894e23a532/href">https://medium.com/media/7b405d6ff9649ac7ebf627894e23a532/href</a></iframe><p>Burada kısaca Prometheus’daki metric tiplerinin üzerinden geçecek olursak:</p><ul><li>Gauge, ile zaman içinde artıp azalan metriklerimizi tanımlayabiliriz. Bizim örnegimizdeki kampanya sayısı artıp azalan bir metrik örnegidir ya da anlık olarak işlenen excel sayısı vb.</li><li>Counter, ile zaman içinde artacak sayısı sürekli artacak metrikleri tanımlayabiliriz. Bir kuyrukta işlenen mesaj sayısı ya işlenen sipariş sayısı gibi zaman içinde sürekli artacak işlem sayısı olarak düşünebiliriz</li><li>Histogram, ile iki zaman aralığı içindeki işlem sayılarımızı ve limitler belirleyerek yüzdelerini ölçebiliriz. Bir kuyruktaki işlemlerin error yüzdesi ya da apdex score ve http request süreleri(median, average, %95) olarak düşünebiliriz.</li><li>Summary ile histogramda ki benzer metrikleri oluşturabiliriz.İki metrik tipi arasındaki en önemli fark histogram da metriklerimizi prometheus server da oluşturur iken summary de metric oluşturmak istenirse client de anlık istek yapılarak oluşturulur. daha detaylı karşılaştırmaya <a href="https://prometheus.io/docs/practices/histograms/">buradan</a> ulaşabilirsiniz.</li></ul><p>Uygulama üzerinden aldığımız datalar ile oluşturduğumuz metrikleri artık prometheus’a besleyebiliriz. Spring boot ile geliştirdiğimiz uygulamamız da <a href="https://micrometer.io/docs/registry/prometheus">micrometer ile oluşturduğumuz</a> prometheus metriklerimizi http olarak dışarı açıp prometheus server a uygulamamızı target olarak göstererek metrikleri beslemeye başlayabiliriz.</p><p>Ardından grafana’ya prometheus serverimizi datasource olarak göstererek beslediğimiz metrikleri görseleştirebilir ya zaman içinde ki değişimlerini izleyebiliriz.</p><p>Metriklerimizi görselleştirdiğimiz, alert tanımları yapabildiğimiz ayrıca değişimlerini sorgulayabileceğimiz grafana ise açık kaynaklı bir analitik ve görselleştirme uygulaması, en önemli özelliği ise birden fazla datasource ile uyumlu olabilmesi, <a href="https://play.grafana.org/d/000000012/grafana-play-home?orgId=1">buradan</a> demo uygulama ile kendi dashboard ve alert tanımlarımızı yaparak güzel bir başlangıç deneyimi elde edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gd7XJwMzELPWMOSaZKvBVQ.png" /><figcaption>pim metrics dashboard small showcase</figcaption></figure><p>Son olarak kendi oluşturacağımız metrikleri nasıl kullancacağımızın örnekler ile belirtecek olursak:</p><ul><li>Tanımlayacağımız metrikler ile sistem alert leri tanımlayabiliriz.Örnegin son 5 dk içinde hiç kampanya açılmaması veya hiç sipariş oluşmaması gibi sistem down olasa da süreci durduran herhangi bir konu hakkında daha erken bilgi sahibi olabiliriz.</li><li>Son yirmi dört saat içinde açılacak kampanya sayısı fazla ise ve bu açılacak kampanyalar belirli bir saat aralığına toplanmış ise, örnegin 8 -9 saatleri gibi anlık bir yük olacağını önceden tahmin edebilir sistemlerimizi alert ler ile önceden scale işlemlerini gerçekleştirerek oluşabilecek anlık sistem yüklerini engelleyebiliriz.</li><li>Sistem kullanıcılarına işlem sonuçlarını veya anlık durumları görebileceği bilgilendirme ekranları tasarlayarak süreçleri hakkında bilgilendirmeler sunabiliriz.</li></ul><p>Umarım faydalı bir yazı olmuştur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=808abde7fda3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trendyol-tech/micrometer-ile-prometheus-metrikleri-olu%C5%9Fturma-808abde7fda3">Micrometer ile Prometheus Metrikleri Oluşturma</a> was originally published in <a href="https://medium.com/trendyol-tech">Trendyol Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>