Exploring" Too Many Updates": How to find and fix a code issue for a large number of outward calls
Tags: webdev, programming, java, devops
Published: 2023-07-07 18:59:37

Whether you're a software engineer looking to optimize your code or just eager to understand [runtime analysis](https://dev.to/appmap/how-appmaps-runtime-analysis-finds-performance-and-security-flaws-4p0k), this article will help you think about rules as they relate to code analysis.

In this article, I explore a maintenance rule called "Too Many Updates" and discuss its implications, causes, and mitigation strategies.

## Understanding the rule

At AppMap, we define the "Too Many Updates" rule as a verification process that examines the number of SQL and RPC updates executed by a command function or method within your application. This rule sets a default threshold of five updates in our `default.yml` file. Any function or method that exceeds this threshold triggers the "Too Many Updates" finding to appear in the runtime analysis results. 

In technical terms, this finding corresponds to [CWE-1048](https://cwe.mitre.org/data/definitions/1048.html), which refers to an “invokable control element with a large number of outward calls” [sic]. For simplicity, we'll refer to it as "Too Many Updates" throughout this article.

## Applying the rule

To illustrate the concept, let's consider a real-world example using a Spring Pet Clinic application implemented with Java and the Spring framework. This application allows us to manage owners, pets, and visits for a veterinary clinic. Imagine we have created an owner, and a pet, a bird we have given the name of Jimmy, and added a recent visit to the veterinarian. Now, let's take a closer look at the code and explore the consequences of the "Too Many Updates" finding.

### Setting custom overrides

Before diving into the code, let's first understand how to customize the default threshold for the "Too Many Updates" rule. By creating an `appmap-scanner.yml` file, and running the command, you can override the default settings.

```bash
$ npx @appland/scanner \
    --appmap-dir tmp/appmap \
    --config appmap-scanner.yml \
    ci
```

In the example provided, the warning limit is set to one for demonstration purposes.

```yaml
checks:
  - rule: authzBeforeAuthn
  - rule: http500
  - rule: illegalPackageDependency
    properties:
      callerPackages:
        - equal: actionpack
      calleePackage:
        equal: app/controllers
  - rule: insecureCompare
  - rule: missingAuthentication
  - rule: missingContentType
  - rule: nPlusOneQuery
  - rule: secretInLog
  - rule: slowFunctionCall
    properties:
      timeAllowed: 0.2
      functions:
        - match: Controller#create$
  - rule: slowHttpServerRequest
    properties:
      timeAllowed: 0.5
  - rule: slowQuery
    properties:
      timeAllowed: 0.05
  - rule: tooManyJoins
  - rule: tooManyUpdates
		properties:
			warningLimit: 1
  - rule: unbatchedMaterializedQuery
  - rule: updateInGetRequest
```

However, in practical scenarios, it's recommended to set a more appropriate threshold based on your application's requirements. Now that we can control our threshold let's jump over and view our findings.

### Analyzing findings

To analyze the findings, we'll use AppMap to navigate to the runtime analysis section. The findings table provides a comprehensive overview of all the identified issues. 


![Analyzing Findings 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dm4f0i5f280cll0j5wo3.png)

You can also group the findings by project, date, or category to gain better visibility into your application's maintainability.


![Analyzing Findings 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nb3t9ow7oy8w675w1zip.png)

Examining Example 1

Open the findings report for the "Too Many Updates" finding to understand its causes and implications. In this example, the command performs 47 SQL or RPC updates, as indicated in the event summary.


![Findings Report Example 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n8g910n9tr9kn91i0lqc.png)

When we examine the map, we can observe a sequence diagram representing the execution flow. The presence of this finding suggests potential poor coding practices or architectural flaws in the application.


![Example 1 Sequence Diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hmxhuqaaayotqd0tqqg.png)

It highlights the need to consolidate multiple calls into a more efficient and maintainable structure. In this particular application, this is the result of database migrations being performed during the setup phase for development.

Examining Example 2

Now, let's explore another example to compare and contrast the findings. In this case, the threshold is set to two, and we examine the sequence diagram for the corresponding map finding an action that performs to “updates” in the same function call.


![Example 2 Sequence Diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hpdxpit47ca7ab1rp6xp.png)

This specific scenario involves adding a pet to an owner. We can observe that two updates are performed: one to `INSERT` the pet's information…

```sql
INSERT INTO pets (id, birth_date, name, type_id)`
```

…and another to associate the pet with its owner.

```sql
UPDATE pets SET owner owner_id=? WHERE id=?
```

Unlike the previous example, this finding emphasizes a design choice rather than inherent flaws in the application's architecture. It prompts us to evaluate if these two calls can be consolidated into a single call for improved efficiency and simplicity.

### Selecting a strategy

To address the "Too Many Updates" finding, we have several mitigation strategies at our disposal. 

The first and simplest approach is refactoring the code to consolidate multiple updates into a single call. Often we find that “Too Many Updates” isn’t the result of some large flaw in the design of our application, but rather the result of poor implementation of coding standards and common best practices. 

By reviewing the code and analyzing the sequence diagrams, we can identify opportunities to optimize the number of updates performed. Additionally, if we do find a larger issue at play we can consider architectural changes. Such as reevaluating the structure of services and abstractions, to ensure a more streamlined approach. 

Alternatively, if these issues uncover a security risk in our application, we can employ the use of rate limiting to ensure our application remains performant and secure. These mitigation strategies enhance maintainability, improve code readability, and reduce potential security risks.

Watch the video:

{% youtube TSJWKRJYvaA %}

## Summary

In this article, we explored the "Too Many Updates" maintenance rule and its impact on software engineering practices. 

By understanding the causes, implications, and mitigation strategies, you can effectively optimize your code and ensure a more efficient and maintainable application. 

Remember to review your findings, analyze sequence diagrams, and implement the appropriate refactoring techniques and architectural changes. By doing so, you'll enhance the overall quality and performance of your software.

**Links**
📸 Cover Photo by [Karl Pawlowicz](https://unsplash.com/@karlp?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/photos/QUHuwyNgSA0?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
  

⬇️ Download AppMap for VSCode and JetBrains: https://appmap.io/download

⭐ Star AppMap on GitHub: https://github.com/getappmap

🐦 Follow on Twitter: https://twitter.com/getappmap

💬 Join AppMap Slack: https://appmap.io/slack

ℹ️ Read the AppMap docs: https://appmap.io/docs

📺 Watch AppMap Tutorials: https://www.youtube.com/@appmap


&nbsp;
&nbsp;
&nbsp;

{% user ghamelin %}