<?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 Hossein Zolfi on Medium]]></title>
        <description><![CDATA[Stories by Hossein Zolfi on Medium]]></description>
        <link>https://medium.com/@hossein.zolfi?source=rss-c53da601503a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*CU5vDP9MUqRJlWJMvtQM8Q.jpeg</url>
            <title>Stories by Hossein Zolfi on Medium</title>
            <link>https://medium.com/@hossein.zolfi?source=rss-c53da601503a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:30:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hossein.zolfi/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[The Negotiation You Lose Before It Starts]]></title>
            <link>https://medium.com/@hossein.zolfi/the-negotiation-you-lose-before-it-starts-d4246a6ef801?source=rss-c53da601503a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4246a6ef801</guid>
            <category><![CDATA[blameless]]></category>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[negotiation]]></category>
            <category><![CDATA[batna]]></category>
            <category><![CDATA[book-review]]></category>
            <dc:creator><![CDATA[Hossein Zolfi]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 16:59:54 GMT</pubDate>
            <atom:updated>2026-07-06T16:59:54.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dj_LXseIPyirFhILsRpn2Q.png" /></figure><p><em>Before you can get anyone else to say yes, the negotiator who co-wrote the book on saying yes argues you first have to get yourself to say yes.</em></p><p>Most negotiation advice shares one hidden assumption. It assumes you already know what you want. It also assumes you can stay calm long enough to go get it. William Ury co-wrote the 1981 classic <em>Getting to Yes</em>. For the next three decades, he kept noticing how often that assumption fails in practice. People walk into a negotiation with a clear ask and a solid plan, and lose the conversation anyway, not to the other side’s argument, but to their own fear or anger in the room. His answer to that pattern is a second book, <em>Getting to Yes with Yourself</em> (2015). It is not a sequel full of new tactics for handling other people. Ury calls it the “missing first half”: the hardest negotiation anyone runs is the one they run with themselves, before the other party ever speaks.</p><p>Ury’s claim, stated plainly: the biggest obstacle to a good outcome is usually not the other party. It’s you. More specifically, it’s a small set of reactive habits: judging yourself, blaming others, fearing there isn’t enough to go around, resenting the past, rejecting people who reject you, and assuming any gain for the other side is a loss for you. Ury lays out six steps that dismantle these habits one at a time. Each step makes the next one easier.</p><h3>Watching yourself before you react</h3><p>The first step is a simple mental move. Step back and observe your own reaction before it runs you. Under threat, most people fall into one of three patterns: attack, give in, or avoid. None of the three serve what you actually want. The stress response does the damage. Blood drains from the thinking parts of your brain and rushes into your legs and fists, the parts built to run or fight, while your heart pounds and your mouth goes dry. Ury’s practical fix is to name the feeling out loud, even privately. He gives the example of saying, “Oh, that’s my old friend Fear.” Naming a feeling creates distance from it, so the feeling stops running the show.</p><p>From that same distance, Ury suggests a second move. Keep asking yourself “why” until a surface complaint bottoms out at the real need underneath it. “I want a raise” is a surface complaint. Underneath it might be a need to feel valued. Once you know the real need, more ways to meet it become visible, and a raise stops being the only path to a good outcome.</p><h3>Taking responsibility instead of assigning blame</h3><p>Blame feels good in the moment. It makes you the innocent one. But it also hands your power to the person you’re blaming. Ury’s sharpest example here is corporate, not personal. In 1982, a poisoning scandal hit Tylenol. CEO James Burke chose to recall every bottle nationwide. The recall cost roughly one hundred million dollars, and Burke’s company had not caused the poisoning. He recalled anyway, rather than downplay the problem. The recall, not the deflection, is what saved the brand.</p><p>Ury calls the personal version of this move the “inner BATNA.” BATNA stands for “Best Alternative To a Negotiated Agreement.” Ury coined the term with his original co-author back in 1981, to describe a negotiator’s best fallback if talks fail: another job offer, another buyer, some external option that lowers the cost of walking away. The inner BATNA turns the same idea inward. It is an unconditional commitment to meet your own deepest needs, no matter what the other side does. In the book’s most personal example, Ury describes learning this the hard way through years of his daughter’s surgeries. He chose to manage his own state rather than treat his family’s wellbeing as entirely dependent on how hospital staff behaved. That choice left them calmer, and, he argues, better able to advocate for her.</p><h3>Deciding the universe is on your side</h3><p>Step three answers a question Ury borrows from Einstein: is the universe friendly? Ury argues that answering “no” produces guarded, adversarial behavior. That happens even in people who would rather cooperate. The reason is scarcity: a “no” answer assumes there is not enough to go around, so look out for yourself. Answering “yes,” cultivated through gratitude and a sense of connection to the people around you, produces partners instead of opponents.</p><h3>Staying present in the room</h3><p>Fourth, Ury borrows psychologist Mihaly Csikszentmihalyi’s idea of “flow,” full absorption in the present moment, and applies it to live conversation. Flow is usually built by matching a challenge to a skill. Ury reaches it differently: by letting go. He forgives the past, releases fear about the future, and simply stays in the room. His example is a tense, unscheduled 2002 meeting with Venezuela’s president Hugo Chavez, held during a political crisis. Ury set aside his prepared talking points and listened instead. The conversation opened a door that a rehearsed pitch would have kept shut.</p><h3>Extending respect to people who reject you</h3><p>Fifth: meet exclusion with inclusion. Ury says giving respect is the cheapest concession available, and the one that pays off the most. He also describes hostage negotiators succeeding today by staying polite and refusing to react. That replaces an older approach built on ultimatums, independent of any specific agency’s training. His most vivid case is Azim Khamisa, whose teenage son was murdered by a gang member. Khamisa chose forgiveness over revenge, and later gave the man who killed his son a job.</p><h3>Giving before you take</h3><p>The sixth and final step draws on Adam Grant’s research on givers and takers. Shifting your basic stance from taking to giving is, in Ury’s telling, what turns an ordinary win-win deal into a “win-win-win”: a deal that benefits both parties and the wider community around them.</p><h3>The reframe worth holding</h3><p>Here’s a real reversal worth sitting with. What if “you are your own biggest obstacle” is itself the trap? Naming your own fear or judgment is supposed to create distance from it. But self-observation can just as easily become a new performance of self-judgment. It becomes a quieter version of the same reactive habit, just dressed up as insight. Watching yourself from the balcony only helps if the watching stays curious. If it turns into another verdict on yourself, you have not escaped the trap. You have renamed it.</p><h3>Objections worth taking seriously</h3><p>Chris Voss makes the sharpest objection, laid out in his own book, <em>Never Split the Difference</em> (2016). Voss is a former FBI hostage negotiator, and his argument, in full: the whole BATNA-and-principled-negotiation tradition Ury helped build in 1981 fails against a counterpart who is emotionally hostile, or simply negotiating in bad faith. Staying calm and taking responsibility for your own needs is necessary, Voss’s record suggests, but it is not, by itself, protection against someone working in bad faith. That is a real limit, not a small one: it holds whenever the other side’s behavior, not your own state, is the actual obstacle to a good outcome. The honest answer is to shrink the claim to fit. The inner BATNA is not a promise about how a hostile counterpart will behave. It is a floor: the minimum you need the deal to be worth to you, whatever they do.</p><p>Daniel Kahneman’s research, in <em>Thinking, Fast and Slow</em> (2011), argues against the friendly-universe step specifically. Kahneman’s framing research shows that logically equivalent descriptions of the same situation can produce opposite feelings and choices, purely from the words used to describe them. That is a direct caution against “decide the universe is friendly.” The idea risks being presented as a discovered fact, when it is really a chosen frame. This piece flags that risk directly, rather than letting the reframe pass as settled fact.</p><p>Stephen Covey’s approach, from <em>The 7 Habits of Highly Effective People</em> (1989), lands in a different place: mild support. Covey’s “private victory before public victory” sequence means getting your own house in order before you try to influence anyone else’s. That is the same order of operations as Ury’s six steps, arrived at from an entirely separate tradition of personal-effectiveness writing. Two writers reaching the same structure independently, decades apart, is a small point in the book’s favor.</p><p>Adam Grant’s giver and taker research, first laid out in his book <em>Give and Take</em> and cited by Ury, expanded further in Grant’s own <em>Think Again</em> (2021), backs “give before you take” with real data. That is stronger footing than pure positive thinking. But Grant’s own case for staying a “scientist” about your own beliefs argues the other way here too. The same discipline that values that evidence should keep testing the “friendly universe” belief against experience, rather than fixing it once through a single gratitude practice and calling it settled.</p><h3>Where it lands</h3><p>Ury closes the book with Nelson Mandela, who went through a version of all six steps in prison. He watched himself from the inside. He refused to blame his jailers. He reframed his picture of them. He released his resentment. He extended respect to men who had wronged him. Once released, he gave generously toward reconciliation rather than settling scores.</p><p>Ury’s own summary is that this produces three wins: a win within yourself that no one else can take away, a win with the other party, and a win for the wider world both of you are part of. The book’s real argument is not that these six steps are a formula to run once and file away. It is that the first negotiation, the one nobody puts on the calendar, is the one you are always already having with yourself. It is worth running deliberately instead of by default.</p><p>What would change in your next hard conversation if you treated the negotiation with yourself as the one that actually decides the outcome?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4246a6ef801" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Roles, Adaptability, and the AI Era]]></title>
            <link>https://medium.com/@hossein.zolfi/roles-adaptability-and-the-ai-era-59eeac5276e4?source=rss-c53da601503a------2</link>
            <guid isPermaLink="false">https://medium.com/p/59eeac5276e4</guid>
            <category><![CDATA[organization-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[engineering-management]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Hossein Zolfi]]></dc:creator>
            <pubDate>Sun, 24 May 2026 08:08:47 GMT</pubDate>
            <atom:updated>2026-05-24T08:08:47.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fhN9cccNOeTgZm3I16nqg.png" /><figcaption>In a world of accelerating change, organizations that adapt around value survive.<br>Those attached to rigidd structures become fragile and eventually lose.</figcaption></figure><p>AI is making software faster to build.<br>That does not mean organizations are becoming better at operating it.</p><p>A question I’ve been asked repeatedly in interviews recently made me realize how many companies still think about software teams through assumptions built for a slower era.</p><h3>The Question Behind the Question</h3><p>A question I’ve been asked repeatedly in recent interviews is:</p><p>“What role do you see yourself in?”</p><p>The more I think about that question, the more I wonder what companies are actually trying to evaluate through it.</p><p>Maybe it’s a standard HR question meant to measure self-awareness. Maybe they want to understand whether someone thinks like a manager or an individual contributor. Maybe they are evaluating clarity of thought.</p><p>But regardless of the intention, I think the question itself reveals something deeper about how many organizations still think about software teams.</p><p>My criticism is not that roles are useless. Organizations need ownership, accountability, and coordination. The problem is that many companies still assume roles should be static in a world that is becoming increasingly unstable.</p><p>Especially in software engineering.</p><h3>The Pressure AI Is Accelerating</h3><p>Competition has become brutally compressed. In many markets — particularly unstable ones — a company that stops adapting for even a few months can quickly become irrelevant. At that point, competitiveness is no longer only about who you hire or what technologies you use. Increasingly, it becomes about how adaptable your systems, decisions, and processes are.</p><p>AI is accelerating this pressure.</p><p>What makes the current moment unusual is not simply the existence of AI tools. It is that the foundations of software development itself are shifting faster than many organizations can adapt. We are entering a phase where the cost of building software is decreasing while the complexity of operating reliable systems may actually increase.</p><h3>Development Speed vs Operational Maturity</h3><p>Many teams are still operating with development processes designed for a slower era:</p><ul><li>long planning cycles,</li><li>fragmented ownership,</li><li>manual operational bottlenecks,</li><li>slow deployment confidence,</li><li>and heavy coordination overhead.</li></ul><p>Now imagine those same organizations increasing development speed through AI without improving their operational maturity. The likely outcome is not necessarily innovation. In many cases, it may simply produce:</p><ul><li>more fragile systems,</li><li>more technical debt,</li><li>noisier architectures,</li><li>and longer recovery cycles when failures occur.</li></ul><p>The challenge is no longer just “How fast can we build?”</p><p>The challenge is:</p><ul><li>How quickly can we adapt?</li><li>How reversible are our decisions?</li><li>How cheaply can we recover from being wrong?</li></ul><p>That applies to technologies, architectures, organizational structures, and even roles themselves.</p><h3>Roles as Tools, Not Identities</h3><p>In that kind of environment, I think predefined identity-based roles become less useful than problem-oriented thinking.</p><p>Before understanding a team’s constraints, challenges, technical debt, operational risks, and market pressures, how confidently can anyone define exactly what their role should be?</p><p>A role should be a tool for solving a problem — not an identity that forces reality to fit inside it.</p><p>If the problem changes, the role should be allowed to change too.</p><p>That does not mean people should become directionless generalists. It means adaptability itself becomes a valuable capability.</p><p>When someone says:</p><blockquote>“I define my role based on the problems that need to be solved,”</blockquote><p>that should not automatically be interpreted as confusion.</p><p>In many cases, it may reflect a different way of thinking about value creation.</p><h3>The Organizations That Adapt Faster</h3><p>Because the problems are usually already visible.</p><p>The issue is that organizations often normalize them for so long that nobody questions them anymore:</p><ul><li>slow execution,</li><li>fragile systems,</li><li>irreversible decisions,</li><li>operational bottlenecks,</li><li>and structures optimized for stability in environments that are no longer stable.</li></ul><p>We are entering a period where uncertainty is not an exception. It is becoming the operating environment itself:</p><ul><li>unstable markets,</li><li>rapidly shifting technologies,</li><li>changing workforce expectations,</li><li>and AI transforming the economics of software development.</li></ul><p>In that environment, organizations that remain overly attached to rigid structures may eventually lose to competitors that learn and adapt faster and redefine roles around problems rather than defining problems around roles.</p><p>I’m increasingly curious about how other engineering leaders and senior ICs are thinking about this tradeoff between specialization, adaptability, and organizational structure in the AI era.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59eeac5276e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Go SQL Internals]]></title>
            <link>https://medium.com/@hossein.zolfi/deep-dive-into-go-sql-internals-c15db62478cf?source=rss-c53da601503a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c15db62478cf</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Hossein Zolfi]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 08:07:47 GMT</pubDate>
            <atom:updated>2024-04-02T08:07:47.604Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring Connection Management and Real-World Challenges</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hKHJZQf0ZoAP6dvgAWLexQ.png" /><figcaption>The image made with Copilot. Powered by DALL·E 3.</figcaption></figure><h3>Introduction:</h3><p>In this article, we will explore the inner workings of Go’s SQL and MySQL drivers, uncovering crucial insights for optimizing database interactions and minimizing errors. These insights have been obtained through an in-depth study of the source code of <a href="https://github.com/golang/go/blob/master/src/database/sql/sql.go">Go’s SQL standard library</a> and the <a href="https://github.com/go-sql-driver/mysql">Go MySQL driver</a>.</p><p><strong>Key Points Covered:</strong></p><ul><li><strong>Prepared statements:</strong> Efficient and secure SQL execution.</li><li><strong>Connection lifecycles:</strong> Managing resource usage and pool maintenance.</li><li><strong>Real-world issues:</strong> Addressing common challenges in microservices architecture.</li></ul><p>In the text below, I clarify Go concepts by inlining them. Lowercase terms represent package names, while uppercase terms denote type names. Parentheses indicate methods, while absence implies types. For example, sql.Stmt refers to the Stmt type in the sql package, and Stmt.QueryContext() signifies the QueryContext method on the Stmt type.</p><h4>Why This Article Matters:</h4><p>Exploring these topics offers valuable insights for optimizing application performance, troubleshooting database errors, and delivering seamless user experiences. Let’s uncover the secrets to mastering Go’s SQL and MySQL drivers.<br>Understanding how SQL and MySQL drivers function in Go is essential for building high-performance applications. We can optimize database interactions and handle failures effectively by delving into concepts like prepared statements and connection lifecycles. This knowledge empowers developers to write better code and minimize errors caused by database issues.</p><h3>Prepared Statements</h3><blockquote>A <a href="https://go.dev/doc/database/prepared-statements">prepared statement</a> is SQL that is parsed and saved by the DBMS, typically containing placeholders but with no actual parameter values. Later, the statement can be executed with a set of parameter values.</blockquote><p>The <a href="https://en.wikipedia.org/wiki/Prepared_statement">benefits of prepared statements</a> are:</p><ul><li>efficiency, because they can be used repeatedly without re-compiling</li><li>security, by reducing or eliminating <a href="https://en.wikipedia.org/wiki/SQL_injection">SQL injection</a> attacks</li></ul><p>Using prepared statements for security purposes certainly seems like a good reason, but honestly, the primary motivation behind their usage is efficiency, as I’ll explain further in the rest of this article.</p><h4>Prepared Statements Lifecycle</h4><p>When we want to run a query on the prepared statement, we do the following steps:</p><ol><li><strong>Statement Preparation:</strong> the DB.Prepare() method prepares the SQL statement and returns a sql.Stmt object.</li><li><strong>Query Execution: </strong>When you execute a query using Stmt.Query(), the driver retrieves a connection from the pool, sends the SQL statement to the database server, and waits for the result.</li></ol><h4><strong>Statement Preparation</strong></h4><p>To prepare the statement, the client grabs a connection from the connection pool and sends the query to the DBMS, and the DBMS parses the query and returns the statement ID to the client, and the client builds the sql.Stmt object.</p><h4><strong>Query Execution</strong></h4><p>To execute a query using Stmt.QueryContext(), the client retrieves a connection from the pool. The <a href="https://mariadb.com/kb/en/prepare-statement/">prepared statement’s scope</a> is limited to the connection in which it was created. Therefore, the sql.Stmt must verify whether the connection is prepared. If not, it automatically prepares the connection, sends the parameters, and returns sql.Rows. Subsequently, we utilize Rows.Scan() to retrieve row data. The connection is released upon calling Rows.Close().</p><p>We gain efficiency here as we don’t need to send the whole query string and the DBMS doesn’t need to parse the query whenever we need to run the query. If the QPS (Query Per Second) is high, it makes sense to prepare it first, and then execute it.</p><p>Until now, I’ve outlined two stages in working with connections: grabbing and releasing them.</p><p>Let’s first discuss releasing connections, and then move on to grabbing them.</p><h4>Releasing Connections</h4><p>Once query execution is complete and the result set is processed, the connection is returned to the connection pool, allowing other queries to reuse it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8lbt4pIB3ILha_MPYa0YQ.png" /><figcaption>Releasing a SQL connection in Go: checking for maximum open and idle connections, and handling pending requests.</figcaption></figure><ul><li>If the current number of open connections exceeds the maximum allowed by DB.SetMaxOpenConns(int), idle connections are immediately closed and not returned to the idle list.</li><li>If there&#39;s a pending request for a connection, the idle connection is forwarded to that request; otherwise, if the count of pending connections is lower than the maximum number of idle connections set by DB.SetMaxIdleConns(int), the connection is appended to the list of free connections for later reuse.</li><li>Otherwise, the connection is closed immediately, and DBStats.MaxIdleClosed metric is increased.</li></ul><p>Go doesn&#39;t keep idle connections indefinitely; it cleans them at intervals. The connection cleaner job closes idle connections that have been idle longer than the max idle time, as well as connections with lifetimes greater than the max lifetime. This process ensures idle connections are cleaned up promptly. Two metrics, DBStats.MaxIdleTimeClosed and DBStats.MaxLifetimeClosed, indicate this behavior.</p><p>Internally, three gauge metrics represent these connections: DBStats.Idle, DBStats.OpenConnections, and DBStats.InUse. DBStats.Idle shows the number of idle connections available, while DBStats.InUse indicates the number of connections currently running queries. Finally, DBStats.OpenConnections is the sum of these two metrics.</p><h4>Grabbing Connections</h4><p>Now, let’s delve into the process of managing database connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VMJJdyhv63PLQEXT0xDJQ.png" /><figcaption>Acquiring/Grabbing a SQL connection in Go: reusing existing ones, opening new connections, and managing connection expiry</figcaption></figure><p><strong>Connection Reuse Attempt:</strong><br>When using Go, it attempts to reuse connections from the idle list. It checks the lifetime of each connection. If a connection’s lifetime exceeds the maximum set by DB.SetConnMaxLifetime(time.Duration), it closes the connection and returns driver.ErrBadConn. After two retries, if the error persists, it tries to open a new connection. Before returning the connection, it resets it using its DB driver (for instance, the MySQL driver), which verifies the connection’s liveness.</p><p><strong>Handling Connection Scarcity:</strong><br>If we run out of free connections or are explicitly instructed not to use one, we have two options: establish a new connection or request a connection and wait until it becomes available in the connection pool. In this scenario, it resets the connection. While waiting for a connection to become available, two additional metrics increase: DBStats.WaitCount and DBStats.WaitDuration.</p><h3>Real-World Issues</h3><p>We have some microservices that we develop using the Go programming language. These microservices use a cluster of MariaDB services for data persistence. We use ProxySQL to provide high availability for these services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*UIXK2S1qiAbXi8zifOtW5A.png" /><figcaption>Service architecture with ProxySQL and MariaDB Cluster</figcaption></figure><p>If we fail to fetch data from the DBMS we respond the internal errors to our clients. The failures can be raised in one of the following links: between the application server and the ProxySQL clusters and between the ProxySQL service and MariaDB services. If any of these links fail, it can cause errors when running queries, leading to an increase in the rate of internal errors.</p><p>Let’s examine the issues we have in our production, identify the reasons, and figure out how to fix them.</p><h4>WaitCount is increased</h4><p>One strange thing I’ve been trying to figure out is that, according to our metrics, the count of open connections is only half of the maximum limits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9yIvP6wJVY_QrFtlnBUkg.png" /><figcaption>The number of open connections is stable at around 15</figcaption></figure><p>Therefore, the wait count should not increase, yet it does. If the wait duration does not remain stable, it can affect the response time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoD25u2iQvS2zBgz4PkYFQ.png" /><figcaption>The wait count is increased</figcaption></figure><p>A sudden surge in requests leads to increased connection usage, often not immediately visible due to sampling intervals (every 10–15 seconds). For instance, while one graph shows steady open connections, another may reveal a spike in wait counts, indicating heightened requests. Just 60 additional simultaneous requests can saturate idle connections, causing queues. Relying on a single metric can lead to misconceptions; considering multiple metrics is essential for accuracy.</p><p>To resolve this issue, consider increasing the maximum open connections (DB.SetMaxOpenConns(int)). If raising this limit isn’t feasible due to the total number of application instances surpassing the overall allowed maximum connections, you may need to reduce the number of application instances before increasing the max open connections.</p><h4>Internal Errors have increased</h4><p>My exploration found that while Go’s SQL standard library attempts to reset connections for availability checks, it doesn’t entirely fix invalid connection errors. An example error, such as unexpected EOF, impacts response times, increases internal errors, and dissatisfies users. Investigation revealed that improperly tuned DBMS-related server parameters, like ProxySQL or MariaDB, cause this issue.</p><pre>Error #01: invalid connection<br>[mysql] 2024/03/29 16:49:43 packets.go:37: unexpected EOF</pre><p>MySQL <a href="https://mariadb.com/docs/server/ref/mdb/system-variables/wait_timeout/">terminates idle connections after </a><a href="https://mariadb.com/docs/server/ref/mdb/system-variables/wait_timeout/">wait_timeout</a>, but ProxySQL isn&#39;t notified, leading to erroneous assumptions of connection status.</p><p>To address this, reduce mysql-ping_interval_server_msec to match or be lower than wait_timeout. This prompts ProxySQL to check idle connections and avoid redirecting requests to terminated connections.</p><p>Using these settings will also resolve the following warnings from ProxySQL entirely.</p><pre>mariadb3 | 2024–03–28 21:07:34 591 [Warning] Aborted connection 591 to db: &#39;mydb&#39; user: &#39;app&#39; host: &#39;172.25.0.5&#39; (Got timeout reading communication packets)<br>Then it gets the following error when the app tries to open new connection:<br>proxysql | 2024–03–28 21:08:56 MySQL_Session.cpp:1694:handler_again___status_PINGING_SERVER(): [ERROR] Detected a broken connection while during ping on (1,mariadb2,3306,604) , FD (Conn:80 , MyDS:80) , user app , last_used 0ms ago : 2006, MySQL server has gone away</pre><p>The ProxySQL <a href="https://proxysql.com/documentation/global-variables/mysql-variables/#mysql-connection_max_age_ms">will not close connections</a>, resulting in the above error being logged.</p><blockquote>By default, connections aren’t closed based on their age. When <em>mysql-connection_max_age_ms</em> is reached, connections are simply disconnected, without sending <em>COM_QUIT</em> command to the server, so this might result in <em>Aborted connection</em> warnings showing up in your MySQL server logs (this behaviour is intended, see <a href="https://github.com/sysown/proxysql/issues/1861">GH #1861</a>).</blockquote><h4>Max Open Connections</h4><p>Consider this scenario: if the max_connections value in ProxySQL is set to 99 and we configure the max open connections in our application to 100, testing across my machine (as detailed in Explore It Yourself) showed a 99.5% uptime, with 0.5% of responses resulting in internal errors.</p><p>The ProxySQL logs the following warning:</p><pre>proxysql  | 2024-03-30 19:38:05 MySQL_Session.cpp:5504:handler___status_CONNECTING_CLIENT___STATE_SERVER_HANDSHAKE(): [WARNING] User &#39;app&#39; has exceeded the &#39;max_user_connections&#39; resource (current value: 99)</pre><p>This scenario emphasizes the importance of accurately tuning parameters.</p><h3>Recommendations</h3><h4>Client Side Recommendations</h4><p>There are good recommendations mentioned in the Go-SQL-Driver’s <a href="https://github.com/go-sql-driver/mysql?tab=readme-ov-file#important-settings">Readme</a>:</p><blockquote><em>db.SetConnMaxLifetime()</em> is required to ensure connections are closed by the driver safely before connection is closed by MySQL server, OS, or other middlewares. Since some middlewares close idle connections by 5 minutes, we recommend timeout shorter than 5 minutes. This setting helps load balancing and changing system variables too.</blockquote><blockquote><em>db.SetMaxOpenConns()</em> is highly recommended to limit the number of connection used by the application. There is no recommended limit number because it depends on application and MySQL server.</blockquote><blockquote><em>db.SetMaxIdleConns()</em> is recommended to be set same to <em>db.SetMaxOpenConns()</em>. When it is smaller than <em>SetMaxOpenConns()</em>, connections can be opened and closed much more frequently than you expect. Idle connections can be closed by the <em>db.SetConnMaxLifetime()</em>. If you want to close idle connections more rapidly, you can use <em>db.SetConnMaxIdleTime()</em> since Go 1.15.</blockquote><p>To summarize the quote, configure sql.DB as follows:</p><pre>db.SetConnMaxLifetime(...) // set it to be smaller than wait_time settings<br>db.SetConnMaxIdleTime(...) // same as db.SetConnMaxLifetime<br>db.SetMaxOpenConns(...)    // max_connections limits divided by number of pods<br>db.SetMaxIdleConns(...)    // same as db.SetMaxOpenConns</pre><p>You&#39;ll discover the max_connections settings by executing the specified queries:</p><pre>ProxySQL Admin&gt; select hostgroup_id, hostname, max_connections from mysql_servers;<br>+--------------+----------+-----------------+<br>| hostgroup_id | hostname | max_connections |<br>+--------------+----------+-----------------+<br>| 0            | mariadb1 | 20              |<br>| 1            | mariadb2 | 300             |<br>| 1            | mariadb3 | 300             |<br>+--------------+----------+-----------------+<br><br>ProxySQL Admin&gt; select username, max_connections from mysql_users;<br>+----------+-----------------+<br>| username | max_connections |<br>+----------+-----------------+<br>| root     | 25              |<br>| app      | 300             |<br>+----------+-----------------+<br><br>ProxySQL Admin&gt; select * from global_variables where variable_name in (&#39;mysql-wait_timeout&#39;) order by variable_name;<br>+--------------------+----------------+<br>| variable_name      | variable_value |<br>+--------------------+----------------+<br>| mysql-wait_timeout | 60000          |<br>+--------------------+----------------+<br><br>mysql&gt; show variables where Variable_name in (&#39;max_connections&#39;,&#39;wait_timeout&#39;);<br>+-----------------+-------+<br>| Variable_name   | Value |<br>+-----------------+-------+<br>| max_connections | 300   |<br>| wait_timeout    | 600   |<br>+-----------------+-------+</pre><p>Based on these values, we should set the connection&#39;s max lifetime to a maximum of 60 seconds. If we run 3 instances of an application, the max open connections should be set to 100.</p><pre>db.SetConnMaxLifetime(60 * time.Second)<br>db.SetConnMaxIdleTime(60 * time.Second)<br>db.SetMaxOpenConns(100)<br>db.SetMaxIdleConns(100)</pre><h4>Server Side Recommendations</h4><p>Adjust mysql-ping_interval_server_msec based on wait_timeout. It should be smaller or equal to wait_timeout, not greater. There’s no point in pinging a connection already terminated by the MySQL server.</p><pre>ProxySQL Admin&gt; select * from global_variables where variable_name in (&#39;mysql-ping_interval_server_msec&#39;) order by variable_name;<br>+---------------------------------+----------------+<br>| variable_name                   | variable_value |<br>+---------------------------------+----------------+<br>| mysql-ping_interval_server_msec | 120000         |<br>+---------------------------------+----------------+</pre><p>The returned result indicates that the configuration is not set up properly. The appropriate values should be less than 60000 msec (60 seconds). It&#39;s worth mentioning that <a href="https://proxysql.com/documentation/global-variables/mysql-variables/#mysql-ping_interval_server_msec">ProxySQL&#39;s default value</a> is 10000 msec (10 seconds).</p><h3>Explore It Yourself</h3><p>To get started, clone the <a href="https://github.com/empire/db-prepared-stmt">source code repository</a>. Ensure that you have the Go, <a href="https://k6.io/">K6</a>, and Docker binaries installed on your system.</p><pre>git clone git@github.com:empire/db-prepared-stmt.git</pre><p>Next, navigate to the galera directory and start the MariaDB cluster using Docker Compose:</p><pre>cd galera<br>docker compose up --remove-orphans</pre><p>Once the cluster is up and running, execute the service by running the following command:</p><pre>go run .</pre><p>To simulate a sample load, you can either use the k6 command or run the run_watched.sh script. To monitor MySQL resources and process lists conveniently, I’ve created a script called monitor.sh. You can execute it using the command watch -n 1 ./monitor.sh.</p><p>If you need to customize the configuration, open the galera/docker-compose.yml and galera/proxysql/proxysql.cnf files. Make the necessary changes to the variables, and then restart the Docker Compose command.</p><h3>Conclusion</h3><p>Understanding the inner workings of Go’s SQL and MySQL drivers empowers developers to optimize database interactions and address potential failures effectively. Developers can enhance application performance and minimize internal errors by leveraging prepared statements, managing connection lifecycles, and applying best practices.</p><p>My exploration uncovered key insights into efficient resource management and troubleshooting techniques, particularly in distributed systems. By implementing recommended configurations and staying informed about database technologies, developers can ensure the smooth operation of their applications and deliver exceptional user experiences.</p><h3>References &amp; Useful links:</h3><ul><li><a href="https://go.dev/doc/database/prepared-statements">Go Prepared Statement Documentation</a></li><li><a href="https://github.com/go-sql-driver/mysql?tab=readme-ov-file#important-settings">Go SQL Driver Readme</a></li><li><a href="https://mariadb.com/kb/en/prepare-statement/">MariaDB Prepared Statement Documentation</a></li><li><a href="https://mariadb.com/docs/server/ref/mdb/system-variables/wait_timeout/">MariaDB Wait Timeout Documentation</a></li><li><a href="https://en.wikipedia.org/wiki/Prepared_statement">Wikipedia Prepared Statement Page</a></li><li><a href="https://proxysql.com/documentation/global-variables/mysql-variables/#mysql-ping_interval_server_msec">ProxySQL ping_interval_server_msec Setting</a></li><li><a href="https://proxysql.com/documentation/global-variables/mysql-variables/#mysql-connection_max_age_ms">ProxySQL connection_max_age_ms Setting</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c15db62478cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code review: people over code]]></title>
            <link>https://medium.com/@hossein.zolfi/code-review-people-over-code-78b3be75b56?source=rss-c53da601503a------2</link>
            <guid isPermaLink="false">https://medium.com/p/78b3be75b56</guid>
            <category><![CDATA[learning-and-development]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[people-first]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hossein Zolfi]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 15:30:58 GMT</pubDate>
            <atom:updated>2023-09-27T15:30:58.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNx0NWoeRHNf1q8gK7YOZg.png" /></figure><p>Code review is a crucial practice for ensuring the quality and maintainability of a codebase. However, it is important to remember that code review is not just about finding and fixing bugs. It is also an opportunity for developers to learn and grow.</p><h4>Why are people more important than code in code review?</h4><p>There are a few reasons why people are more important than code in code review:</p><ul><li><strong>Happy developers write better code.</strong> When developers feel respected, supported, and challenged, they are more likely to produce high-quality code. They are also more likely to be engaged and motivated to contribute to the team.</li><li><strong>Code can be changed, but people are more difficult to change.</strong> It is easier to fix a bug in the code than it is to change a developer’s attitude or behavior. This is why it is important to focus on creating a positive and supportive code review environment, where developers feel comfortable giving and receiving feedback.</li><li><strong>A positive code review environment is more conducive to learning and growth.</strong> When developers feel comfortable asking questions and giving feedback, they are more likely to learn from each other and improve their skills. This is beneficial for both the individual developer and the team as a whole.</li></ul><h4>How to focus on people in code review</h4><p>Here are a few tips for focusing on people in code review:</p><ul><li><strong>Be respectful and supportive.</strong> Avoid using language that is critical or judgmental. Instead, focus on providing constructive feedback that can help the developer improve. Be sure to acknowledge the developer’s work and effort, even if you have suggestions for improvement.</li><li><strong>Be open-minded and collaborative.</strong> Be willing to listen to the developer’s perspective and understand their reasoning. Don’t insist on having your way. Be willing to compromise and find solutions that work for everyone involved.</li><li><strong>Focus on learning and growth.</strong> Use code review as an opportunity to help developers learn and grow. Ask open-ended questions and encourage discussion. Share your own knowledge and experience. Help the developer to identify areas where they can improve and develop a plan for doing so.</li></ul><p>By following these tips, you can help to create a more positive and productive code review environment, where both the code and the people involved improve.</p><h4>Additional tips</h4><p>Here are a few additional tips for focusing on people in code review:</p><ul><li><strong>Be timely.</strong> Don’t wait until the last minute to give feedback. The sooner you can give feedback to a developer, the easier it will be for them to make the changes.</li><li><strong>Be specific and actionable.</strong> When giving feedback, be as specific as possible about what you think needs to be improved. Also, try to provide actionable suggestions for how the developer can make the improvement.</li><li><strong>Focus on constructive criticism.</strong> When giving feedback, avoid using language that is critical or judgmental. Instead, focus on specific suggestions for improvement.</li></ul><p>By following these tips, you can help to make code review a more positive and productive experience for everyone involved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78b3be75b56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A radical idea to keep the service up!- Part One]]></title>
            <link>https://medium.com/@hossein.zolfi/a-radical-idea-to-keep-the-service-up-part-one-1bf69f454b4f?source=rss-c53da601503a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bf69f454b4f</guid>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Hossein Zolfi]]></dc:creator>
            <pubDate>Wed, 25 Dec 2019 11:46:42 GMT</pubDate>
            <atom:updated>2019-12-25T11:46:42.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4IzShewf9h205rUn3wuiA.jpeg" /></figure><p>Keeping software services up &amp; running is one of the great challenges. There are various ways to ensure that software services are always up and running.</p><p>In this I article, I focus on the second part, and I’ll answer “How to Make Sure Software Services Stay Up.”</p><p>The simplest approach is “if ain’t broke, don’t fix it”. But this is an old approach and has many problems in practice. Our approach to our Paydar team is the opposite.</p><blockquote>If you are afraid of what you are doing, and if it hurts, do it more often.</blockquote><p>It is simple, but it is a radical idea!</p><p>The question may come to your mind, “Why should we do this?” Let me answer it with a simple example.</p><p>Suppose you have a DBMS that has not been restarted for a long time and you are afraid of restarting it as it may not come up after restarting or causing other services to crash. What do you do!?</p><p>For a variety of reasons, the real world may not fit your assumptions. What happens if the system crashes for whatever reason (such as power failure, UPS failure, your colleague doing something bad, hardware and software errors, applying security updates, operating system updates by another group) then it is not clear, what will be happening, when the service becomes up, it is unclear how long it will take for the service to resume.</p><p>Now suppose you can get rid of this dilemma by using the same methods (which I will mention in future posts). But until then, let me put it in a very simple way: <strong>specify the exact version of the applications used in the services, and to keep the application version fixed</strong>. As an example of a Python service, the following items are important and needed to be fixed:</p><ul><li>Specify the exact version of Python, for example, 3.8.0</li><li>Python modules, such as Ansible 2.7.15</li><li>The operating system on which Python is installed, such as Ubuntu 16.04.06</li><li>Fix version of packages installed in the operating systems</li><li>Disconnect services from the Internet</li></ul><p>For each of the above, there are various mechanisms that I will address in the future.</p><p>But these are the only side of the story. Another important part is to set up software mechanisms that support the above simple method. Keeping the software version fixed without these mechanisms is a bit tedious. In the future, I will answer the question of “How to ensure that the above method works?”</p><p>Let me go back to the question, “How do we ensure that a software service stays up against changes?”</p><p><strong>The first step is to keep the dependencies fixed, then change the dependency version to a fully tested and controlled one</strong>. I will write about other mechanisms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bf69f454b4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>